简体   繁体   English

new而不是Object.create

[英]new instead of Object.create

Normally I'm doing it that way: 通常我是这样做的:

$.fn.MYPL = function (options) {
   return this.each(function () {
      myplg = Object.create(MYPL);
      myplg.init(options, this);
   });
};

Object.create is not supported in IE6, IE7, and IE8. IE6,IE7和IE8不支持Object.create I just realized, that I can replace Object.create with new like: 我刚刚意识到,可以用new代替Object.create ,例如:

var g = new Graph();

But I have no idea.. How to change my plugin definition? 但是我不知道..如何更改我的插件定义?

I've tried: 我试过了:

var myplg = new MYPL();

But it's not working. 但这不起作用。 Any help appreciated. 任何帮助表示赞赏。

您可以填充工具Object.create ,这样就可以在IE7和IE8使用它。

I saw the MDN polyfill did not support anything with a properties object, so I wrote a slightly more complete implementation which will at least let you set value and warn about others if there is a console available and also throws the right kind of error messages. 我看到MDN polyfill不支持属性对象的任何内容,因此我编写了一个稍微完整的实现,这至少可以让您设置并在有可用控制台的情况下警告其他人,并且还会抛出正确的错误消息。

if (!Object.create) {
    Object.create = (function () {
        function _Object() {}

        return function(proto, props) {
            var o, k, d;
            if (proto !== null && typeof proto !== 'object')
                throw new TypeError('Object prototype may only be an Object or null');
            _Object.prototype = proto;
            o = new _Object();
            for (k in props) {
                if (typeof props[k] !== 'object')
                    throw new TypeError('Property description must be an object: ' + props[k]);
                for (d in props[k])
                    if (d === 'value')
                        o[k] = props[k].value;
                    else
                        if (console && console.warn)
                            console.warn('Object.create implementation does not support: ' + d);
            }
            return o;
        };
    }());
}

Object.create(MYPL) sets object prototype. Object.create(MYPL)设置对象原型。 For constructor-based approach you can try the following code: 对于基于构造函数的方法,您可以尝试以下代码:

function MYPLConstructor() {}

for (var key in MYPL) {
     MYPLConstructor.prototype[key] = MYPL[key];
}

var myplg = new MYPLConstructor();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM