prototype----> 每个构造函数拥有--new构造函数时会将prototype对象作为构造函数的this,构造函数在上面挂载属性或者方法
constructor--->构造函数
proto ---> 每一个实例对象拥有--是相当于constructor中的this
疑惑 person.prototype里面的prototype有什么用
//这段代码注释掉constructor结果依旧一样
function Person(name,age) {
this.name = name
this.age = age
}
var Student = function(name,age,grade) {
Person.call(this,name,age)
this.grade = grade
}
// Student继承Person
Student.prototype = Object.create(Person.prototype,{
// constructor: {
// value: Student
// },
getGrage: {
value: function() {
return this.grade
}
}
})
var p = new Student("Lin",20,100)
console.log(p.age)
console.log(p.name)
console.log(p.grade)
Object.create(o,....)是指创建一个对象以o作为这个对象的__proto __ 后面参数可以和defineProperty一样给这个对象添加字段
constructor是原型对象上的一个属性,默认指向这个原型的构造函数。
如果我们没有指定的话或者指定错误,会导致原型链指向不正确,更深层的原型链指向错误会造成什么后果我就不知道了。除非是浏览器js引擎还有什么特殊的用途?
实现原型实现继承
function Person(name,age) {
this.name = name;
this.age = age;
}
Person.prototype.getName = function() {
return this.name
}
function Student(name,age,grade) {
Person.call(this,name,age);
this.grade = grade
}
// 先实例化构造函数的prototype 然后传入构造函数--让其添加属性
Student.prototype = Object.create(Person.prototype,{
constructor: {
value: Student
},
getGrade: {
value: function() {
return this.grade
}
}
})
st = new Student("lin",21,100)
st.getName()
st.getGrade()
defineProperty
ES6自定义字段允许更多的特性
//writeable和set会冲突 value和get会冲突
var a = {}
Object.defineProperty(a,'name',{
configurable:false,
enumerable:false,
//writable:false,
//value:"lin",
get() {
//这里不能用this访问,否侧会无限递归想想为什么
return name
},
set(v) {
name = v
}
});
console.log(a.name) //lin
a.name = "ren"
console.log(a.name) //lin