IE8 中的 JavaScript getter 支持

发布于 12-10 17:00 字数 924 浏览 0 评论 0原文

查看此代码。这是一个非常简单的 JavaScript 对象,它是使用 模块模式 实现的(你可以请参阅此小提琴地址的实时示例)

var human = function() {
    var _firstName = '';
    var _lastName = ''
    return {
        get firstName() {
            return _firstName;
        }, get lastName() {
            return _lastName;
        }, set firstName(name) {
            _firstName = name;
        }, set lastName(name) {
            _lastName = name;
        }, get fullName() {
            return _firstName + ' ' + _lastName;
        }
    }
}();
human.firstName = 'Saeed';
human.lastName = 'Neamati';
alert(human.fullName);

但是,IE8不支持JavaScript get设置关键字。您可以对其进行测试并查看 MDN

我应该怎么做才能使这个脚本也兼容 IE8?

Check out this code. This is a very simple JavaScript object which is implemented using Module Pattern (and you can see the live example at this fiddle address)

var human = function() {
    var _firstName = '';
    var _lastName = ''
    return {
        get firstName() {
            return _firstName;
        }, get lastName() {
            return _lastName;
        }, set firstName(name) {
            _firstName = name;
        }, set lastName(name) {
            _lastName = name;
        }, get fullName() {
            return _firstName + ' ' + _lastName;
        }
    }
}();
human.firstName = 'Saeed';
human.lastName = 'Neamati';
alert(human.fullName);

However, IE8 doesn't support JavaScript get and set keywords. You can both test it and see MDN.

What should I do to make this script compatible with IE8 too?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

心碎无痕…2024-12-17 17:00:49

我应该怎样做才能使这个脚本也兼容 IE8?

彻底改变它。例如,不要使用访问器属性,而是使用普通属性和函数的组合:

human.firstName = 'Saeed';
human.lastName  = 'Neamati';
alert(human.getFullName());

其他人建议在 IE 中使用 DOM 对象并使用 Object.defineProperty() 添加属性。虽然它可能有效,但出于多种原因,我强烈建议不要使用这种方法,例如您编写的代码可能并不在所有浏览器中兼容:

var human = document.createElement('div');
Object.defineProperty(human, 'firstName', { ... });
Object.defineProperty(human, 'lastName',  { ... });
Object.defineProperty(human, 'children',  { value: 2 });

alert(human.children);
//-> "[object HTMLCollection]", not 2

至少 Chrome 是这样。无论哪种方式,编写可在您想要支持的所有浏览器上运行的代码都会更安全、更轻松。您通过编写代码来利用 getter 和 setter 所获得的任何便利,都因您专门针对 Internet Explorer 8 编写的额外代码而失去了。

当然,除了性能下降之外,您还需要将无法在对象上使用 for...in 循环,并且当您使用您认为已定义但预先存在于 DOM 对象上的属性时,可能会出现混乱。

What should I do to make this script compatible with IE8 too?

Change it completely. For example, instead of using accessor properties, use a combination of normal properties and functions:

human.firstName = 'Saeed';
human.lastName  = 'Neamati';
alert(human.getFullName());

Somebody else suggested using a DOM object in IE and adding the properties using Object.defineProperty(). While it may work, I'd highly recommend against this approach for several reasons, an example being that the code you write may not be compatible in all browsers:

var human = document.createElement('div');
Object.defineProperty(human, 'firstName', { ... });
Object.defineProperty(human, 'lastName',  { ... });
Object.defineProperty(human, 'children',  { value: 2 });

alert(human.children);
//-> "[object HTMLCollection]", not 2

This is true of at least Chrome. Either way it's safer and easier to write code that works across all the browsers you want to support. Any convenience you gain from being able to write code to take advantage of getters and setters has been lost on the extra code you wrote specifically targeting Internet Explorer 8.

This is, of course, in addition to the reduction in performance, the fact that you will not be able to use a for...in loop on the object and the potential confusion ensuing when you use a property you thought you defined but was pre-existing on the DOM object.

残龙傲雪2024-12-17 17:00:49

你不能(安迪回答

最接近的替代方案是

var human = function() {
    var _firstName = '';
    var _lastName = '';

    return {
        firstName: function() {
            if (arguments.length === 1) {
                _firstName = arguments[0];
            }
            else {
                return _firstName;
            }
        },
        lastName: function() {
            if (arguments.length === 1) {
                _lastName = arguments[0];
            }
            else {
                return _lastName;
            }
        },
        fullName: function() {
            return _firstName + ' ' + _lastName;
        }
    };
}();

human.firstName('Saeed');
human.lastName('Neamati');

alert(human.fullName());

演示 http://jsfiddle.net/gaby/WYjqB/2/

You cannot (as Andy answered)

The closest alternative would be

var human = function() {
    var _firstName = '';
    var _lastName = '';

    return {
        firstName: function() {
            if (arguments.length === 1) {
                _firstName = arguments[0];
            }
            else {
                return _firstName;
            }
        },
        lastName: function() {
            if (arguments.length === 1) {
                _lastName = arguments[0];
            }
            else {
                return _lastName;
            }
        },
        fullName: function() {
            return _firstName + ' ' + _lastName;
        }
    };
}();

human.firstName('Saeed');
human.lastName('Neamati');

alert(human.fullName());

Demo at http://jsfiddle.net/gaby/WYjqB/2/

雨后咖啡店2024-12-17 17:00:49

IE8 支持 DOM 节点上的 getter 和 setter,因此如果您确实想要有 getter 和 setter,您可以这样做:

var objectForIe8 = $("<div></div>")[0];    
Object.defineProperty(objectForIe8, "querySelector", {
    get: function() {
        return this.name;
    },
    set: function(val) {
        this.name = val+", buddy";  
    }
});
// notice you can overwrite dom properties when you want to use that property name
objectForIe8.querySelector = "I'm not your guy"; 

alert(objectForIe8.querySelector);

注意,这会给您带来一定程度的性能损失,所以如果您需要创建数千个,我不会使用此技术像这样的物体。但如果您不担心这个特定对象的性能,它会让您渡过难关。如果您不太关心 ie8 性能,而只是希望它能够工作,那么仅对 ie8 使用此技术,您就很出色了:)

IE8 supports getters and setters on DOM nodes, so if you really want to have getters and setters, you can do this:

var objectForIe8 = $("<div></div>")[0];    
Object.defineProperty(objectForIe8, "querySelector", {
    get: function() {
        return this.name;
    },
    set: function(val) {
        this.name = val+", buddy";  
    }
});
// notice you can overwrite dom properties when you want to use that property name
objectForIe8.querySelector = "I'm not your guy"; 

alert(objectForIe8.querySelector);

Note this gives you a somewhat significant performance hit, so I wouldn't use this technique if you need to create thousands of objects like this. But if you're not worried about performance of this particular object, it'll tide you over. And if you couldn't care less about ie8 performance, and just want it to work, use this technique for ie8 only and you're golden : )

救星2024-12-17 17:00:49

检查 http:// /robertnyman.com/2009/05/28/getters-and-setters-with-javascript-code-samples-and-demos/

扩展对象的未来和 ECMAScript 标准化方式
各种方式都是通过Object.defineProperty。就是这样
Internet Explorer 选择实现 getter 和 setter,但它是
不幸的是,到目前为止仅在 Internet Explorer 8 中可用,在
任何其他网络浏览器。另外,IE 8 仅在 DOM 节点上支持它,但是
未来的版本计划在 JavaScript 对象上支持它
好吧。

您可以在同一站点 http://robertnyman 找到测试用例。 com/javascript/javascript-getters-setters.html#object-defineproperty

Object.defineProperty(document.body, "description", {
    get : function () {
        return this.desc;
    },
    set : function (val) {
        this.desc = val;
    }
});
document.body.description = "Content container";

结果:

document.body.description = "Content container"

Check it on http://robertnyman.com/2009/05/28/getters-and-setters-with-javascript-code-samples-and-demos/

The future, and ECMAScript standardized way, of extending objects in
all sorts of ways is through Object.defineProperty. This is how
Internet Explorer chose to implement getters and setters, but it is
unfortunately so far only available in Internet Explorer 8, and not in
any other web browser. Also, IE 8 only supports it on DOM nodes, but
future versions are planned to support it on JavaScript objects as
well.

You can find the test cases on the same site at http://robertnyman.com/javascript/javascript-getters-setters.html#object-defineproperty

Object.defineProperty(document.body, "description", {
    get : function () {
        return this.desc;
    },
    set : function (val) {
        this.desc = val;
    }
});
document.body.description = "Content container";

Result:

document.body.description = "Content container"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文