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