課程
/前端開發
/JavaScript
/JavaScript深入淺出
People.call(this,name,age)換成this=new Person(name,age)有區別嗎?
2016-08-06
源自:JavaScript深入淺出 8-1
正在回答
Person.call(this,name,age); ?其中的Person是指視頻中的構造函數:
function Person(name,age){
? ? this.name = name;
? ? this.age = age;
}
Person.call(this,name,age);其中的call是指Function.prototype.call(),其中的this在其上下文中指向Student對象。
因此,Person.call(this,name,age);是調用Person構造函數,并把Person構造函數中的this替換為傳入的this參數所代表的Student對象,因此Student對象便繼承了name和age兩個屬性。
Person.call(this,name,age);這一句是讓Student繼承了Person中屬性,并沒有影響this指針。
而this=new Person(name,age);這一句將改變this指針的值使其變為Person類型的對象。因此通過Student構造器返回的對象為this是一個Person類型的對象。后面對Student.prototype所做的設置應該對返回的Person類型的對象不起作用。
qq_放飛心情_0 提問者
舉報
由淺入深學習JS語言特性,且解析JS常見誤區,從入門到掌握
2 回答繼承的問題
1 回答JS繼承問題
1 回答類繼承問題
1 回答關于抽象類中繼承的問題
1 回答關于 原型的繼承 這一節的一個疑問
Copyright ? 2025 imooc.com All Rights Reserved | 京ICP備12003892號-11 京公網安備11010802030151號
購課補貼聯系客服咨詢優惠詳情
慕課網APP您的移動學習伙伴
掃描二維碼關注慕課網微信公眾號
2016-08-06
Person.call(this,name,age); ?其中的Person是指視頻中的構造函數:
function Person(name,age){
? ? this.name = name;
? ? this.age = age;
}
Person.call(this,name,age);其中的call是指Function.prototype.call(),其中的this在其上下文中指向Student對象。
因此,Person.call(this,name,age);是調用Person構造函數,并把Person構造函數中的this替換為傳入的this參數所代表的Student對象,因此Student對象便繼承了name和age兩個屬性。
2016-08-06
Person.call(this,name,age);這一句是讓Student繼承了Person中屬性,并沒有影響this指針。
而this=new Person(name,age);這一句將改變this指針的值使其變為Person類型的對象。因此通過Student構造器返回的對象為this是一個Person類型的對象。后面對Student.prototype所做的設置應該對返回的Person類型的對象不起作用。