静态方法和实例方法

参考下面博客:

JavaScript 静态方法和实例方法

总结: 直接定义在构造函数上的方法和属性是静态的,  定义在构造函数的原型和实例上的方法和属性是非静态的

静态方法:

function ClassA(){ //定义构造函数
};
ClassA.func = function(){ //在构造函数上添加一个属性(因为函数也是对象)
    console.log("This is a static method");
}
var instance = new ClassA(); //新建一个实例
ClassA.func(); //This is a static method
instance.func(); //Error:instance.func is not a function

非静态方法:

// 定义在构造函数原型上的方法是实例方法 
function ClassA(){ //定义构造函数
};
ClassA.prototype.func = function(){ //在构造函数的原型上添加方法
    console.log("This is an instance method.");
}
var instance = new ClassA(); //新建一个实例
ClassA.func();  // Error:ClassA.func is not a function
instance.func(); //This is an instance method.

// 定义在某个具体对象(实例)上的方法是实例方法
function ClassA(){ //定义构造函数
};
var instance = new ClassA(); //新建一个实例
instance.func = function(){
    console.log("This is an instance method.")
}
// ClassA.func();  // Error:ClassA.func is not a function
instance.func(); //This is an instance method.

可以在构造函数中直接为这个类所有对象绑定属性和方法:(这里还不是很理解)

function ClassA(){ //定义构造函数
    var method1 = function(){  //内部函数, 在外部不能访问 
        console.log("method1");
    }
    this.method2 = function(){ //为新创建的实例绑定方法
        console.log("method2");
        method1(); // 调用method1(),闭包使得method1()可以保存下来, 也就是说在构造函数调用之后还能继续使用.
    }
    this.method3 = function(){
        console.log("method3");
        this.method2(); // 调用对象已经绑定了的method2().
    }
};

var instance = new ClassA();
instance.method3();

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值