javascript对象(如array&一串

Are there lifecycle callback functions for javascript objects such as array & string

本文关键字:amp 一串 array 对象 javascript      更新时间:2023-10-16

好吧,伙计们,我已经在搞原型有一段时间了,还没有准备好放弃它们的有用性。。。尽管受到严厉批评!

我正在与CCD_ 1属性在其他对象(如数组&字符串。即:

Object.defineProperty(
    Object.prototype, 'jsf',
    {get:function(){
        return JSON.stringify(this);
    }};
);
x = {abc: 123};
y = document.createElement('div');

如果你正在阅读这一页,你是!,那么你就会知道,因为CCD_;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();
    }}
);

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

x.ms.jsf = {"abc": 123}
y.ms.jsf = undefined
y.ms.str = <div></div>
x.ms.str = undefined

不管喜欢与否,我都不想键入前缀Object.prototype0,它很不整洁,坦率地说,很碍事!

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

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就不会被修改,也不会从一个对象向下一个对象泄漏属性。。。???!!!

你怎么看?有可能吗?如果有,怎么做?

您可以使用try/catch:

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