我有一个关于您如何定义原型(prototype)属性的问题。所以您不必编写“MyClass.prototype”。为了将每个属性添加到原型(prototype)中,人们创建了新对象并将其设置为原始对象。
像这样。
var MyClass = function() {}
MyClass.prototype = {
sayHi : function() {
alert('hi');
}
}
但是如果您这样做,当您尝试从任何实例访问构造函数时可能会导致问题。
var o1 = new MyClass();
alert( o1 instanceof MyClass ); // true
alert( o1.constructor === MyClass ); // false !!!
o1.constructor
通常会指向 MyClass,但由于原始原型(prototype)已更改,因此不再指向。
我设法通过 MyClass.prototype.constructor = MyClass;
解决了这个问题,它再次正常工作。
问题是,改变原始原型(prototype)会导致哪些其他问题?
您如何定义原型(prototype)属性?
最佳答案
我通常使用简单的 defclass
函数在 JavaScript 中彻底创建“类”:
function defclass(prototype) {
var constructor = prototype.constructor;
constructor.prototype = prototype;
return constructor;
}
这个函数允许我创建类如下:
var MyClass = defclass({
constructor: function () {},
sayHi: function () {
alert("hi");
}
});
该方法具有以下优点:
- 所有原型(prototype)属性都封装在一个对象文字中。
constructor
函数本身只是另一个原型(prototype)属性。- 实例将始终具有正确的
constructor
属性。
例如:
var o1 = new MyClass;
alert(o1 instanceof MyClass); // true
alert(o1.constructor === MyClass); // true
您还可以轻松修改defclass
以支持继承:
function defclass(uber, body) {
var base = uber.prototype;
var prototype = Object.create(base);
var constructor = body.call(prototype, base), prototype.constructor;
constructor.prototype = prototype;
return constructor;
}
然后您可以按如下方式使用它:
var Rectangle = defclass(Object, function () {
this.constructor = function (width, height) {
this.height = height;
this.width = width;
};
this.area = function () {
return this.width * this.height;
};
});
继承也同样简单:
var Square = defclass(Rectangle, function (base) {
this.constructor = function (side) {
base.constructor.call(this, side, side);
};
});
一切如期进行:
var sq = new Square(5);
alert(sq.area()); // 25
alert(sq instanceof Square); // true
alert(sq instanceof Rectangle); // true
alert(sq.constructor === Square); // true
这就是所有人。
关于javascript - 定义原型(prototype)属性的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20644493/