js中静态方法、原型方法、实例方法

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
  • 4
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值