我正在开发一个迷你游戏项目,目的是学习 javascript、node 等。我对所有这些都是新手,我想知道如何以正确的方式创建原型(prototype),尤其是使用 requireJS。我对它和模块等了解得越多,我就越困惑;-) 例如
我怎样才能用我喜欢的括号表示法编写下面的对象,因为它会节省我很多“this”并使其更具可读性......
define([],function(){
Ball = function(){
this.x = null,
this.y = null,
this.vel = null
};
Ball.prototype.serve = function(){};
Ball.prototype.update = function(){};
Ball.prototype.render = function(){};
return Ball;
});
当我用括号表示法编写它时,出现错误,Ball 不是函数。
define([],function{
var Ball = {
x: null,
y: null,
vel: null
};
Ball.prototype.serve = function(){};
Ball.prototype.update = function(){};
Ball.prototype.render = function(){};
return Ball;
});
以及如何使用 requrejs 继承正确的方式。
非常感谢。
最佳答案
要使用对象作为原型(prototype)(而不是第一个示例中的构造函数原型(prototype)),请使用 Object.create
。
对象不具有用于建立继承的 prototype
属性,而使用 new
调用函数时则具有该属性
var Ball = {
x: null,
y: null,
vel: null,
serve: function() {},
update: function() {},
render: function() {}
};
var ballInstance = Object.create(Ball);
可视化这一点的一个好方法是理解这一点
function MyClass(y) {
this.y = y;
}
MyClass.prototype.x = 'x';
var myClass = new MyClass('yVal')
与
是一样的var myClass = Object.create(MyClass.prototype);
MyClass.call(myClass, 'yVal');
关于Javascript 对象括号表示法和 requirejs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35871631/