Object.prototype .__ defineGetter __(和__defineSetter __)polyfill [英] Object.prototype.__defineGetter__ (and __defineSetter__) polyfill

查看:108
本文介绍了Object.prototype .__ defineGetter __(和__defineSetter __)polyfill的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道__defineGetter__(和__defineSetter__)方法名称确实是

I know the __defineGetter__ (and __defineSetter__) method name is really weird and deprecated but I find it more convenient than Object.defineProperty. Compare yourself:

//Readable
Something.prototype.__defineGetter__("name", function() {return this._name;});
//Uh... - what?
Object.defineProperty(Something.prototype, "name", {
                       get: function() {return this._name;}
                     });

因为,正如我所说,此方法已被弃用.因此,我正在创建一个polyfill以使其恢复到正常状态:

Because, as I said, this method is being deprecated. So I'm creating a polyfill to put it back in bussiness:

if(!Object.prototype.__defineGetter__) {
  Object.prototype.__defineGetter__ = function(name, func) {
    Object.defineProperty(this, name, {
      get: func
    });
  }
}

它实际上只是称为标准Object.defineProperty.我可以根据需要命名__defineGetter__.我只是决定坚持已有的东西.

It really just calls the standard Object.defineProperty. I could name the __defineGetter__ whatever I wanted. I just decided to stick to something that already existed.

这里的问题是,如果我在同一属性上使用__defineGetter____defineSetter__填充,我会两次调用Object.defineProperty.

The problem here is that if I use __defineGetter__ and __defineSetter__ polyfills on the same property, I'm calling Object.defineProperty twice.

我的问题是:可以在同一属性上两次调用Object.defineProperty吗?例如,它不会覆盖某些内容吗?

My question is: Is it OK to call Object.defineProperty twice on same property? Doesn't it overwrite something for example?

推荐答案

要在再次调用defineProperty时保留旧的setget,则必须在添加getter或setter时将其拔出:

To retain the old set or get when calling defineProperty again, you'll have to pull them out when adding the getter or setter:

var proto = Object.prototype;

proto.__defineGetter__ = proto.__defineGetter__ || function(name, func) {
    var descriptor = Object.getOwnPropertyDescriptor(this, name);
    var new_descriptor = { get: func, configurable: true};
    if (descriptor) {
        console.assert(descriptor.configurable, "Cannot set getter");
        if (descriptor.set) new_descriptor.set = descriptor.set; // COPY OLD SETTER
    }
    Object.defineProperty(this, name, new_descriptor);
};

proto.__defineSetter__ = proto.__defineSetter__ || function(name, func) {
    var descriptor = Object.getOwnPropertyDescriptor(this, name);
    var new_descriptor = { set: func, configurable: true};
    if (descriptor) {
        console.assert(descriptor.configurable, "Cannot set setter");
        if (descriptor.get) new_descriptor.get = descriptor.get; // COPY OLD GETTER
    }
    Object.defineProperty(this, name, new_descriptor);
};

这篇关于Object.prototype .__ defineGetter __(和__defineSetter __)polyfill的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆