2022-07-04连看4篇前辈的文章,记录一些知识点1.

2022-07-04

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

1. constructor

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

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

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

顺便带一下js中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对象储存需要共享的属性和方法

分类:

技术点:

相关文章:

© 版权声明
THE END
喜欢就支持一下吧
点赞299赞赏 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容