function Parent(age ){ this.age = age } Parent.prototype.run = function(){ return `age is ${this.age}` } function Child(age){ Parent.call(this,age) //對象冒充, (第2次調用Parent) } Child.prototype = new Parent(); // 原型連接繼承, (第一次調用Parent) var test = new Child(20); console.log(test.run())
上面寫法 有個小問題是: Parent會調用2次 javascript
改進 : 實現組合式繼承的時候,Child.prototype = Object.create(Parent.prototype)
java
function Parent(age ){ this.age = age console.log('執行'); } Parent.prototype.run = function(){ return `age is ${this.age}` } function Child(age){ Parent.call(this,age) } Child.prototype = Object.create(Parent.prototype); var test = new Child(20); console.log(test.run()) //測試下: Child.prototype.__proto__ ===Parent.prototype //true 完美實現,而且只執行一次Parent
構造函數內部的方法 和它原型對象上的方法區別:app
結合實際需求 看狀況使用了。函數