Js:如何在子class函数中访问父class的对象?
Js: How to access an object of the parent class in a subclass function?
我正在学习Javascript,现在我面临着巨大的问题来适应Js中基于原型的编程。我在下面发布了我的问题的代码:
//This is my parent class
var Entity = function(id)
{
this.self =
{
x:250,
y:250,
id:id,
}
}
//This is the subclass
var Player = function(id)
{
Entity.call(this, id);
this.updatePosition = function()
{
// HOW DO I ACCESS "self" from the parent class here?
// I want to change the x and y variables from the self object
}
}
Player.prototype = Object.create(Entity.prototype);
Player.prototype.constructor = Player;
如果有人能帮助我,我会很高兴!
提前致谢。
this
是您的实例,您的 Player
class 继承了 Entity
的所有属性,包括 .self
。您只需访问坐标 this.self.x
和 this.self.y
;但是你应该重新考虑为什么你需要那个 self
对象,为什么你不把它的属性直接放在实例上。
我正在学习Javascript,现在我面临着巨大的问题来适应Js中基于原型的编程。我在下面发布了我的问题的代码:
//This is my parent class
var Entity = function(id)
{
this.self =
{
x:250,
y:250,
id:id,
}
}
//This is the subclass
var Player = function(id)
{
Entity.call(this, id);
this.updatePosition = function()
{
// HOW DO I ACCESS "self" from the parent class here?
// I want to change the x and y variables from the self object
}
}
Player.prototype = Object.create(Entity.prototype);
Player.prototype.constructor = Player;
如果有人能帮助我,我会很高兴! 提前致谢。
this
是您的实例,您的 Player
class 继承了 Entity
的所有属性,包括 .self
。您只需访问坐标 this.self.x
和 this.self.y
;但是你应该重新考虑为什么你需要那个 self
对象,为什么你不把它的属性直接放在实例上。