js类的封装

    利用js的闭包封装机制

闭包的三个特性:

1.函数嵌套函数

2.函数的内部可以引用外部的变量

3.参数和变量不会被垃圾回收机制回收

闭包的是指有权访问另一个函数作用域中的变量和函数,创建闭包最常见的方式就是在一个函数内创建另一个函数,通过另一个函数访问这个函数的局部变量

1.js中自定义对象。与之对应的是js标准对象 例如Data,Array.Math.等

2.原型(prototype)

在js中,这是一种创建对象属性和方法的方式,通过prototype可以为对象添加新的属性和方法。

通过prototype我们可以为js标准对象添加新的属性和方法,例如对于String对象,我们可以为其添加一个新的方法trim().

定义对象属性

三种类型的属性:私有属性,实例属性和类属性,私有属性只能在对象内部使用,实例必须通过对象的实例来引用,而类属性可以直接通过类名进行引用。

1)私有属性的定义

语法规则:var propertyName=value;

例子:

function User(age){
    this.age=age;
    var isChild = age < 12;
        this.isLittleChild=isChild;
    }
    var user=new User(15);
    alert(user.isLittleChild);//正确的方式
    alert(user.isChild);//报错:对象不支持此属性或方法

2)实例属性定义

prototype方式 语法格式:functionName.prototype.prototypeName=value;

this方式,语法格式:this.prototypeName=value;

例子:

function User(){ }
User.prototype.name=“user1”;
User.prototype.age=18;
var user=new User();
alert(user.age);
—————————————–
function User(name,age,job){
    this.name=“user1”;
    this.age=18;
    this.job=job;
    }
    alert(user.age);

3)类属性定义

语法格式:functionName.prototypeName=value;

function User(){ }
User.MAX_AGE=200;
User.MIN_AGE=0;
alert(User.MAX_AGE);

定义对象方法

1)定义私有方法

私有方法必须在构造函数体内定义,而且只能在构造函数体内使用

语法格式: function methodName(arg1,..,argN){

}

例子:

function User(name){
    this.name=name;
    function getNameLength(nameStr){
        return nameStr.length;
    }
    this.nameLength=getNameLength(this.name);
    }

定义类方法:

语法格式:functionName.methodName=method;

functionName.methodName=function(arg1,…,argN){};

例子:

function User(name){
    this.name=name;
}
User.getMaxAge=getUserMaxAge;
function getUserMaxAge(){
    return 200;
}
或者User.getMaxAge=function(){return 200;};
alert(User.getMaxAge())



 
function ShapeBase() {
this.show = function()
{
alert("ShapeBase show");
};
this.init = function(){
alert("ShapeBase init");
};
}

需要注意的是这里用到了this来声明,而不是var,因为用var是用来定义私有方法的

 
ShapeBase.prototype={
show:function()
{
alert("ShapeBase show");
},
init:function() {
alert("ShapeBase init");
}
};

 
ShapeBase.prototype={
show:function()
{
alert("ShapeBase show");
},
init:function() {
alert("ShapeBase init");
}
};
 
ShapeBase.prototype={
show:function()
{
alert("ShapeBase show");
},
init:function() {
alert("ShapeBase init");
}
};

测试

 function test(src){
var s=new ShapeBase();
s.init();
s.show();
}

对象方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值