先備知識 call()
function test() {
console.log(this)
}
test.call('123')
test.call({})
new 關鍵字做的事
- 產生新的 obj
- call constructor,把 obj 當作 this 丟進去,便完成初始化的物件
- 設定 proto 到指定的 prototype
- 回傳 obj
- 完成 instance
function Dog(name) {
this.name = name
}
Dog.prototype.getName = function() {
return this.name
}
Dog.prototype.sayHello = function() {
console.log(this.name)
}
var d = new Dog('hi')
var b = newDog('hello')
function newDog(name) {
var obj = {}
Dog.call(obj, name)
console.log(obj)
obj.__proto__ = Dog.prototype
return obj
}
b.sayHello()
console.log(b.getName())
參考資源