Edd*_*die 2 javascript prototype
为什么我不能在函数内部设置原型?例如,为什么这不起作用?
var Bar = function(){
this.name='Bar'
}
var barProto = new Bar()
var Foo = function(){
this.prototype= barProto
}
var foo = new Foo()
console.log(foo.name) // undefined
Run Code Online (Sandbox Code Playgroud)
但这确实有效:
var Bar = function(){
this.name='Bar'
}
var barProto = new Bar()
var Foo = function(){
}
Foo.prototype= barProto
var foo = new Foo()
console.log(foo.name) // Bar
Run Code Online (Sandbox Code Playgroud)
我不喜欢在创建函数后分配原型的语法.
this.prototype= barProto
Run Code Online (Sandbox Code Playgroud)
不等于
Foo.prototype= barProto
Run Code Online (Sandbox Code Playgroud)
this 指的是由新的Foo()创建的特定对象
Foo是构造函数.您在构造函数上设置原型,而不是在特定实例上.
有关原型继承的更多信息:Mozilla docs