是否有针对数组和字符串等javascript对象的生命周期回调函数
好了,伙计们,我已经和原型玩了一段时间了,现在还不准备放弃它们的有用性。。。尽管遭到严厉批评 我正在与其他对象(如数组和字符串)中Object.prototype属性继承这一由来已久的问题作斗争。即:是否有针对数组和字符串等javascript对象的生命周期回调函数,javascript,object,callback,lifecycle,Javascript,Object,Callback,Lifecycle,好了,伙计们,我已经和原型玩了一段时间了,现在还不准备放弃它们的有用性。。。尽管遭到严厉批评 我正在与其他对象(如数组和字符串)中Object.prototype属性继承这一由来已久的问题作斗争。即: Object.defineProperty( Object.prototype, 'jsf', {get:function(){ return JSON.stringify(this); }}; ); x = {abc: 123}; y = documen
Object.defineProperty(
Object.prototype, 'jsf',
{get:function(){
return JSON.stringify(this);
}};
);
x = {abc: 123};
y = document.createElement('div');
如果你正在阅读本页,并且你是!,然后您就会知道,由于x&y都是对象,基于x或y的类型,x&y都将继承jsf属性,因此:
x.jsf = {"abc": 123}
y.jsf = Uncaught TypeError: Converting circular structure to JSON
现在我知道有各种各样的工作循环,比如:
Object.defineProperty(y, 'jsf', {value: void 0});
我最喜欢的是:
function Master_Object(){ this.jsf = JSON.stringify(this) }
function Master_Element(){ this.str = this.outerHTML }
Object.defineProperty(
Object.prototype, 'ms',
{get:function(){
cons=this.constructor.name;
if(cons=='Object') return new Master_Object();
else if(cons=='HTMLDivElement') return new Master_Element();
}}
);
其中每个对象只有一个可管理的自定义属性.ms,该属性是一个包含对象构造函数特定属性的对象,因此:
x.ms.jsf = {"abc": 123}
y.ms.jsf = undefined
y.ms.str = <div></div>
x.ms.str = undefined
问题是,我似乎无法将这些回调转换为用于对象范围而不是元素范围
如果我能按照以下思路写一些东西,我会省去很多麻烦:
Object.defineProperty(
Object.prototype, 'createdCallback',
{value: function(){
var Proto_Clone = Object.create(Object.prototype);
var cons = this.constructor.name;
if(cons == 'Object'){
Object.defineProperty(Proto_Clone,'...',{value:...});
}
else if (cons == ...) ...;
this.prototype = Proto_Clone;
}}
);
其思想是,当一个对象被实例化时,将对其执行检查以确定其构造函数,如果所述构造函数是对象,则在解析之前将其原型更改为修改后的原型克隆
这样,原始Object.prototype永远不会被修改,并且不会从一个对象泄漏到下一个对象
那你觉得呢?是否可能,如果可能,如何实现?您可以使用try/catch:
Object.defineProperty(
Object.prototype, 'jsf',
{get:function(){
try {
return JSON.stringify(this);
} catch (e) {
return undefined;
}
}};
);
对不起,伙计,它仍然让我的所有对象都有一个未定义的.jsf属性。。。我自己也可以避免。
Object.defineProperty(
Object.prototype, 'jsf',
{get:function(){
try {
return JSON.stringify(this);
} catch (e) {
return undefined;
}
}};
);