[英]Why can't I set a JavaScript prototype inside a function?
Why can't I set the prototype inside of a function? 为什么不能在函数内部设置原型? For example why does this not work?
例如,为什么这不起作用?
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
But this does work: 但这确实有效:
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
I don't like the syntax of assigning the prototype after I have created the function. 我不喜欢在创建函数后分配原型的语法。
this.prototype= barProto
is not equivalent to 不等于
Foo.prototype= barProto
this
refers to a specific object which will be created by new Foo() this
是指将由new Foo()创建的特定对象
Foo is the constructor function. Foo是构造函数。 You set the prototype on the constructor, not on a specific instance.
您将原型设置在构造函数上,而不是在特定实例上。
More info on prototypical inheritance here: Mozilla docs 有关原型继承的更多信息,请参见: Mozilla文档
Because this.prototype
is not the same as Foo.prototype
. 因为
this.prototype
与Foo.prototype
。 When Foo
is called with new
, any reference to this
inside it will refer to the instance being created. 当
Foo
时调用new
,任何参考this
里面就会引用被创建的实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.