是否存在javascript对象的生命周期回调函数,例如array&串

时间:2015-02-12 20:51:30

标签: javascript object callback lifecycle

好的家伙我现在已经搞好了一段时间的原型,并且还没准备好放弃它们的用处......尽管受到了严厉的批评!

我在其他对象(例如数组和数组)中与Object.prototype属性继承的古老问题作斗争。字符串。即:

Object.defineProperty(
    Object.prototype, 'jsf',
    {get:function(){
        return JSON.stringify(this);
    }};
);

x = {abc: 123};
y = document.createElement('div');

如果你正在阅读这个页面,而你就是!,那么你就会知道,因为x& y是基于typeof xy的对象,x& y将继承jsf属性,即ergo:

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();
    }}
);

其中每个对象只有1个可管理的自定义属性.ms,并且该属性是包含特定于对象构造函数的属性的对象,因此:

x.ms.jsf = {"abc": 123}
y.ms.jsf = undefined

y.ms.str = <div></div>
x.ms.str = undefined

最喜欢与否我不想输入前缀.ms,它不整洁而且坦率地说道路!

我一直在玩自定义元素,我知道生命周期的回调,以及它们如何跟踪元素的进展......

var proto = Object.create(HTMLElement.prototype);

proto.createdCallback = function() {...};
proto.attachedCallback = function() {...};

var XFoo = document.registerElement('x-foo', {prototype: proto});

我似乎无法将这些回调转换为在对象范围内使用而不是元素范围?!

如果我能按照以下方式写一些东西,那将会省去很多麻烦:

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那么它的原型就被改为修改了在解析之前Proto_Clone

这样原来的Object.prototype永远不会被修改,并且没有属性从一个对象泄漏到下一个...... ??? !!!

那你觉得怎么样?是否可能,如果是这样的话?

1 个答案:

答案 0 :(得分:0)

你可以使用try / catch:

Object.defineProperty(
    Object.prototype, 'jsf',
    {get:function(){
        try {
            return JSON.stringify(this);
        } catch (e) {
            return undefined;
        }
    }};
);