我试图最大限度地重用一些代码.在我的自定义javascript对象上(为了简单起见,我将使用PhoneNumber作为示例),我正在设置这样的原型函数:
var Map = {
write: function() {
alert('My object is ' +this);
}
};
function PhoneNumber(number) {
this.number = number;
}
PhoneNumber.prototype = Map;
//I can call the write function like so
var phoneObject = new PhoneNumber('1234567894');
phoneObject.write(); //ALERT My Object is Object{number:'1234567894'}
Run Code Online (Sandbox Code Playgroud)
一切正常,除了由于某种原因它将我的电话号码对象变成通用对象而不是保持其PhoneNumber构造函数.如果我实际上将write函数放在这样的对象原型中,它就可以完美地工作.
function PhoneNumber(number) {
this.number = number;
}
PhoneNumber.prototype.write = function() {
alert('My object is ' +this);
}
var phoneObject = new PhoneNumber('1234567894');
phoneObject.write(); //ALERT My object is PhoneNumber{number:'1234567894'}
Run Code Online (Sandbox Code Playgroud)
但我真的不必这样做,因为多个对象使用write函数,它们都执行完全相同的方式.如何避免我的对象转换为通用构造函数?显然我正在以错误的方式在原型上设置Map对象,但是非常重要的是我不必将代码直接从Map复制到对象原型函数中.有任何想法吗?
你忘记设置了PhoneNumber.prototype.constructor
当你这样做时,PhoneNumber.prototype = Map你会销毁构造函数属性
PhoneNumber.prototype = Map;
PhoneNumber.prototype.constructor = PhoneNumber;
Run Code Online (Sandbox Code Playgroud)
当然,这是行不通的,因为如果您用作多个原型,Map.constructor = PhoneNumber您所做的就会中断。Map所以你应该让 PhoneNumber 从 map 继承
PhoneNumber.prototype = Object.create(Map, {
constructor: { value: PhoneNumber }
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3314 次 |
| 最近记录: |