尝试为HTML5 Canvas(JavaScript)创建一个小的自定义库,但无法弄清楚如何将自定义实体类的动态原型方法绑定到拥有原型的对象 - 而是将方法绑定到原型对象它们是以......提供的,例如:
var map = new Map({
map: '#canvas'
});
var Rectangle = map.entity({
name: 'Rectangle',
constructor: function(x, y, width, height) {
// Here, `this` refers to the instantiated object
this.x = x;
this.y = y;
this.width = width;
this.height = height;
},
prototype: {
moveTo: function(x, y) {
// Here, `this` refers to the object containing this function - prototype
this.x = x;
this.y = y;
}
}
});
包含#moveTo(prototype)的对象是#moveTo中绑定的this
,但我希望它绑定到构造函数中引用的对象。
这是MapInstance#entity ...
entity: function(name, constructor, prototype, supers) {
if (Object.prototype.toString.call(name) === '[object Object]') {
name.supers = name.supers || {};
this[name.name] = name.constructor || function() {};
var p = name.prototype || name.constructor.prototype;
for (var i = 0; i < name.supers.length; i++) {
for (var m in name.supers[i].prototype) {
p[m] = name.supers[i].prototype[m];
}
}
name.constructor.prototype = p;
} else {
supers = supers || {};
this[name] = constructor;
var $p = prototype || constructor.prototype;
for (var j = 0; j < supers.length; j++) {
for (var f in supers[j].prototype) {
$p[f] = supers[j].prototype[f];
}
}
constructor.prototype = $p;
}
return name.constructor || constructor;
}
我分别在第9行和第19行尝试了p [m] .bind(name.constructor)和$ p [f] .bind(构造函数),但是this
仍然引用了持有原型方法的对象。
如何将它绑定到构造函数中的this
的值?