[英]What happens in JavaScript when defining objects on Constructor Variables
Say I have defined a Constructor and a prototype in Javascript like this: 假设我已经用Javascript定义了一个Constructor和一个原型,如下所示:
MyGame.Player = function(){
this.somevar = 42;
};
MyGame.Player.prototype = {
somevar: null,
someFunc: function(){}
};
What will happen if I do the following: 如果执行以下操作会发生什么:
MyGame.Player.Helper = function(){...}
MyGame.Player.Helper.prototype = {...}
Will javascript allow this actually?
javascript会允许这个吗?
Sure. 当然。 It's just a function as property of an object.
它只是作为对象属性的功能。 In classical OOP this would be called a class method .
在经典OOP中,这称为类方法 。
Will the Helper appear as ownProperty in an instance of MyGame.Player()?
帮助程序会在MyGame.Player()的实例中显示为ownProperty吗?
Nope. 不。 It's a property of the constructor function , not of the instance.
它是构造函数的属性,而不是实例的属性。 The instance only gets all properties assigned to
this
in the constructor and anything from the prototype
. 实例仅在构造函数中获取分配给
this
所有属性,并且从prototype
任何内容。 It doesn't inherit properties of the constructor function. 它不继承构造函数的属性。
Can I always create new Helper objects even if I don't have a Player object?
即使没有Player对象,我也可以始终创建新的Helper对象吗?
Sure, because you call new MyGame.Player.Helper
, not new (new MyGame.Player).Helper
. 当然,因为您调用的是
new MyGame.Player.Helper
,而不是new (new MyGame.Player).Helper
。
Put another way, you just assigned a function to MyGame.Player.Helper
, of course you can call it via MyGame.Player.Helper()
, because that's where you just put it. 换句话说,您刚刚为
MyGame.Player.Helper
分配了一个函数,当然您可以通过MyGame.Player.Helper()
调用它,因为这就是您放置它的地方。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.