Student.prototype.constructor = Student是什么意思???
Student.prototype.constructor = Student是什么意思???我理解的是將Student的prototype初始化為Student,但是沒想明白這樣做的原因。
bosn是屬于Student的,Student的prototype從Person初始化回了Student。那么問題來了,為啥bosn會追蹤到Student后繼續追蹤到之前定義的Person?
Student.prototype.constructor = Student是什么意思???我理解的是將Student的prototype初始化為Student,但是沒想明白這樣做的原因。
bosn是屬于Student的,Student的prototype從Person初始化回了Student。那么問題來了,為啥bosn會追蹤到Student后繼續追蹤到之前定義的Person?
2015-01-10
舉報
2015-01-10
該部分會在原型鏈、OOP相關得章節詳細展開討論。
簡單說,當定義一個構造器(函數)時,該構造器就會有prototype屬性,prototype.constructor指向這個構造器本身:
function?Student()?{ } Student.prototype.constructor?===?Student;?//?true當用該構造器創建Student實例時,就可以通過constructor判斷是由Student構造的。
該constructor屬性并不是bosn這個對象上的,而是從原型鏈(Student.prototype)上來的。
bosn.hasOwnProperty('constructor');?//?false當出于實現繼承的目的而修改了構造器Student.prototype時,Student.prototype.constructor已經不是Student了,為了避免誤解,手動重設Student.prototype.constructor屬性,這樣通過new Student創建的實例的constructor又可以正確取道Student了。
更多詳情,關注后續課程更新吧:)
2018-08-07
我給你測試了一下
Student.prototype = new Person;
Student.prototype.constructor?= Student; ( 這句不寫)
console.log(Student.prototype.constructor);
//
? Person(name,age){
? ? this.name = name;
? ? this.age = age;
}
>>>>>>>>>>
Student.prototype.constructor?= Student; ( 寫上這句)
//
? Student(name,age,className){
? ? Person.call(this,name,age);
? ? this.className = className;
}
>>>>>>>>>>
Student.prototype.constructor?= Person; ( 指向Person)
//
? Person(name,age){
? ? this.name = name;
? ? this.age = age;
}