js静态方法、原型方法和实例方法的主要区别:
类型 | 说明 | 访问者 |
---|---|---|
静态方法 | 定义在构造函数上的方法 | 只能被构造函数访问 |
原型方法 | 通过构造函数的prototype定义的方法 | 能被实例直接访问,构造函数需通过prototype才可访问 |
实例方法 | 构造函数中this上添加的属性都属于实例属性 | 只能被实例对象访问 |
请看下面的示例,将说明三者的区别。
// 构造函数
function People(color) {
this.color = color;
this.seeColor = function() {
console.log("color is "+this.color)
}
}
// 静态方法
People.say = function() {
console.log("静态方法color is ", this.color)
}
// 原型方法
People.prototype.eat = function() {
console.log("原型方法color is ", this.color)
}
// 实例
var pp = new People();
// 调用静态方法
People.say(); // 静态方法color is undefined
pp.say(); // 报错信息:Uncaught TypeError: pp.say is not a function
// 调用原型方法
People.eat(); // 报错信息:Uncaught TypeError: People.eat is not a function
pp.eat(); // 原型方法color is Red
// 调用实例方法
People.seeColor(); // Uncaught TypeError: People.seeColor is not a function
pp.seeColor(); // color is Red