IE8中的JavaScript getter支持 [英] JavaScript getter support in IE8

查看:334
本文介绍了IE8中的JavaScript getter支持的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

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

推荐答案


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

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

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

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

至少Chrome是这样。无论哪种方式,编写适用于您想要支持的所有浏览器的代码都更安全,更容易。您编写代码以利用getter和setter所获得的任何便利都会因您专门针对Internet Explorer 8编写的额外代码而丢失。

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.

这是,当然,除了性能降低之外,你还无法在中使用来循环对象,以及随后可能产生的混淆您使用您认为已定义但在DOM对象上预先存在的属性。

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.

这篇关于IE8中的JavaScript getter支持的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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