function Person(name) {
this.name = name;
}
// construcotr放属性是因为属性一般是不一定的,而方法是固定的。
// prototype声明的属性,隐性,console.log时不显示,但可枚举
Person.prototype.greet = () => {
console.log('hello')
}
// new一个实例时,其属性值先继承prototype,然后construcotr里可变动。
// prototype和construcotr里的初始属性不是同一个东西,尽管他们都会影响new出来的实例
function Teacher(name) {
//继承construcotr方法
Person.call(this, name)
}
// 继承prototype的属性和方法
Teacher.prototype = Object.create(Person.prototype)
// 此时 Teacher.prototype.constructor == Person //true
// 改变构造函数指向
Teacher.prototype.constructor = Teacher;
// practice
let Button = function () {
this.type = 'button';
this.display = true;
}
Button.prototype.display = false;
Button.prototype.xxx = false;
let btnA = new Button();
console.log(btnA.display) // true
for (let i in btnA) {
console.log(i); // 有xxx属性
}
console.log(btnA.__proto__==Button.prototype) // true 官方不推荐使用__proto__
let fkBtn = function () {
this.type = 'fakebutton';
}
fkBtn.prototype = Object.create(Button.prototype)
console.log(fkBtn.prototype == Button.prototype) // false
console.log(fkBtn.prototype, Button.prototype) // Button {} Button { display: false, xxx: false } //fkBtn.prototype 不显示继承的,但可枚举
console.log(fkBtn.prototype.__proto__ == Button.prototype) //true 官方不推荐使用__proto__
console.log(fkBtn.prototype.constructor==Button) // true
fkBtn.prototype.constructor = fkBtn
console.log(fkBtn.prototype.constructor==Button) // false
console.log(fkBtn.prototype.constructor==fkBtn) // true
复制代码
转载于:https://juejin.im/post/5c3eb2846fb9a049b780a227