js中prototype,constructor的理解

连看4篇前辈的文章,记录一些知识点

  1. Javascript继承机制的设计思想

  2. Javascript 面向对象编程(一):封装

  3. Javascript面向对象编程(二):构造函数的继承

  4. Javascript面向对象编程(三):非构造函数的继承

1. constructor

在Javascript语言中,new命令后面跟的不是类,而是构造函数(constructor)。

创建一个叫Student的构造函数,表示学生对象的原型

function Student(name){
    this.name = name;
  }

顺便带一下js中this的用法 Javascript 的 this 用法

对这个构造函数使用new,会生成Student的实例

var st1 = new Student("lilei")
console.log(st1.name) // lilei

此时st1 会自动含有一个属性constructor,指向构造函数

console.log(st1.constructor == Student) //true

用构造函数生成实例对象(使用new),有一个缺点,那就是无法共享属性和方法

比如说有同学韩梅梅和同学李雷,他们共同在太阳班

function Student(name){
    this.name = name;
    this.class = "sun";
}
var st1 = new Student("lilei")
var st2 = new Student("hanmeimei")

输出二人的班级

console.log(st1.class)//sun
console.log(st2.class)//sun

班级改名,修改李雷的班级为月亮班
韩梅梅的班级名称没有发生变化,依然是sun(太阳班)

st1.class = "moon"
console.log(st1.class) //moon
console.log(st2.class) //sun

所以,构造函数中的共有属性无法做到数据共享,要做到数据共享,需要用到prototype

2. prototype

构造函数设置有prototype属性,属性中包含一个对象,需要共享的属性和方法,放在prototype对象里
。不需要共享的属性和方法,放在构造函数里

将上述例子改写

function Student(name){
    this.name = name;
}
Student.prototype = {class : "sun"}

var st1 = new Student("lilei")
var st2 = new Student("hanmeimei")

st1.prototype.class = "moon"
console.log(st1.class) //moon
console.log(st2.class) //moon

每一个实例都有一个constructor属性,默认调用prototype的constructor属性

st1.constructor  = st1.prototype.constructor

总结:
constructor储存不需要共享的属性和方法,而prototype对象储存需要共享的属性和方法

转载于:https://www.cnblogs.com/gggggggxin/p/10070496.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值