js的面向对象初探

js的面向对象

1. 所有的函数都是Function类的对象

2. 静态方法 可以访问静态变量 不可以访问成员变更

非静态方法 类中直接this 可以访问私有变量,可以访问成员变量,prototype 不可以访问私有变量,可以访问成员变量

私有方法 可以访问私有变量,不可以通过this访问成员变量,this为window

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);


ecmascript:
http://www.ecmascript.cn/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值