![](/img/trans.png)
[英]How to add / replace values in a nested object (without losing original references) in Javascript?
[英]How to extend Object in JavaScript without losing the original functionality
我有一个像这样定义的JavaScript对象:
var Object = (function () {
function Object() {
this.id = RandomNumber();
}
// Custom Object.prototype / Object impementations here...
return Object;
})();
问题是,一旦构建它,它就会失去像Object.defineProperty
等原始功能。
我的想法是,我想扩展Object的基本功能,而不是重写或覆盖现有的原型。
怎么能实现这一目标?
编辑:为了清楚,我知道我可以做到这一点而不影响原来的功能:
Object.prototype.foo = function() { }
但我需要专门为Object的构造函数添加功能,即
function Object() { this.id = 0; }
新功能不得覆盖原始功能。
使用.prototype
添加属性:
Object.prototype.specialMethod = function () {
// Your method's code
};
你会像以下一样使用它:
var a = {};
a.specialMethod();
虽然我不鼓励在Object
的原型中添加属性,因为它是可枚举的并且会使循环陷入混乱,并且将被所有对象和从Object
继承的Object
继承,这基本上就是一切。
您实际上可以使用您提到的Object.defineProperty
方法:
Object.defineProperty(Object.prototype, "specialMethod", {
enumerable: false, // The important one, to avoid looping problems
configurable: false,
writable: false,
value: function () {
// Your method's code
}
});
为了扩展此对象,您应该创建另一个对象,该对象的原型分配了一个新的Object实例。
var Object = (function () {
function Object() {
this.id = 5;
}
Object.prototype.speak = function(prop){
alert(this[prop]);
}
return Object;
})();
function ExtendsObject(prop){
this.someProperty = prop;
}
ExtendsObject.prototype = new Object();
var xObj = new ExtendsObject("derived");
xObj.speak("id");
xObj.speak("someProperty");
工作示例: http : //jsfiddle.net/RbCcA/
如果你想坚持使用自执行函数,那么重写的例子是:
var Object = (function () {
function Object() {
this.id = 5;
}
Object.prototype.speak = function(prop){
alert(this[prop]);
}
return Object;
})();
var ExtendsObject = (function(){
function ExtendsObject(prop){
this.someProperty = prop;
}
ExtendsObject.prototype = new Object();
return ExtendsObject;
})();
var xObj = new ExtendsObject("derived");
xObj.speak("id");
xObj.speak("someProperty");
工作示例: http : //jsfiddle.net/RbCcA/1/
我确实质疑在这种情况下使用自执行功能。 它们通常用于封装和屏蔽内部,但在代码示例中,它们通过从SEF返回对象来暴露。 返回对象并将其存储在全局变量中只需重新公开对象,从而允许对其原型和属性进行操作。 也许你没有提到私人变量,但正如所述,我发现SEF是不必要的。
就像伊恩写的那样。 如果您还想检查它已经存在的方法使用
if (Object.prototype.specialMethod == null) Object.prototype.specialMethod = function() { ... };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.