js的面向对象
1. 所有的函数都是Function类的对象
2. 静态方法 可以访问静态变量 不可以访问成员变更
非静态方法 类中直接this 可以访问私有变量,可以访问成员变量,prototype 不可以访问私有变量,可以访问成员变量
3. prototype属性是个对象,改对象的方法无法通过函数直接访问。需要new出实例来访问,new实例的时候,prototype的所有方法都会被复制到实例中
具体可以参考如下代码实例,关键的地方都有注释:
//此函数将变成所有函数的静态方法
Function.prototype.adda = function ()
{
console.log(1);
}
function testa(b)
{
//私有变量
var a = b;
//成员变量,不通过new访问时,this为window
this.a = b;
//私有方法
function testa4()
{
a = 5;
this.a=6;
}
//非静态方法
this.testa1 = function ()
{
console.log(this.a);
console.log(this.b);
}
this.seta = function (x)
{
a = x;
}
this.geta = function ()
{
testa4();
console.log(a);
console.log(this.a);
}
}
//静态成员
testa.b = 3;
//静态方法
testa.testa2 = function ()
{
//此处this为原函数对象testa,相当于给testa添加静态成员
this.b = 1;
}
//非静态方法
testa.prototype = {
testa3 : function ()
{
console.log(this.a);
}
}
testa.prototype.testa4 = function ()
{
console.log(this.a);
}
ins = new testa(3);
ins.geta();
ins.seta(8);
ins.geta();
console.log(a);