我很清楚JavaScript不是基於類的語言。Javascript如何將值從「超類」傳遞給「子類」
有了這樣說這裏是(途徑之一),我們做的繼承在JavaScript的例子:
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.introduceSelf = function() {
console.log("My name is " + this.name + " and I'm " + this.age);
}
function Employee(name, age, employeeID) {
Person.call(this, name, age);
this.employeeID = employeeID;
}
Employee.prototype = Object.create(Person.prototype);
Employee.prototype.sayEmployeeID = function() {
console.log('My Employee ID is: ' + this.employeeID);
}
var joe = new Employee('Joe', 22, 42);
joe.introduceSelf() // returns: My name is joe and I'm 22
joe.sayEmployeeID() // returns: My Employee ID is: 42
我的問題是:如何簡單地調用內Person.call(this, name, age)
員工構造函數,導致對象在致電時具有name
和age
屬性new Employee(...)
據我所知,它調用Person函數,this
是Employee
中的上下文,但不清楚屬性如何進入結果對象。到底發生了什麼?「引擎蓋下?」
我建議投入大量時間學習JavaScript關閉。 https://開頭計算器。com/questions/111102/how-do-javascript-closures-work – Kris
@Kris與閉包無關,它只是javascript的本質,它在「dynamic」這個指針上運行,它驅動那些不理解它的人瘋。這就是爲什麼你可以在javascript中「借用」函數,常用的模式是'Array.prototype.slice.call(nodeList)'在添加'Array.from'之前將'NodeList'轉換爲數組。' – Dummy
這是因爲當'new'instanceof'Employee'被調用'Person'被稱爲寬度時,'this'被綁定到Employee的instanceof。 – PHPglue