![](/img/trans.png)
[英]Why do we add methods using the prototype property of the constructor function?
[英]Using Prototype of function constructor add new function
我想檢查一下我的想法是否正確?
代碼:
function Person(firstname, lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
Person.prototype.getFullName = function () {
return this.firstname + ' ' + this.lastname;
}
var john = new Person('Melo','Tang');
我將下圖中的代碼稱為“函數構造函數”。
function Person(firstname, lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
程序運行到此行時
var john = new Person('Melo','Tang');
我真的不明白您的圖表或箭頭或它們的顏色應該代表什么。
程序運行到此行時
var john = new Person('Melo','Tang');
此處發生的事情正是通過Person
構造函數以Person.prototype
作為原型構造了一個新對象。 除了用作新對象的原型之外,不檢查或Person.prototype
, Person.prototype
也無法對其上的方法進行任何處理。 僅在查找屬性和方法時john.getFullName()
例如,在調用john.getFullName()
時john.getFullName()
,才查詢原型。
為了清楚起見,我將避免使用術語“函數構造器對象”。 只需將其稱為“構造函數(函數)”即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.