问题描述
我可以安全地扩展Javascript内置类,例如 Array
?
在其上的浏览器/环境将无法工作:
Array.prototype.double = function(){return this.concat这个); }
Array.twice = function(a){return a.double(); }
Array.twice([1,2,3])#=> [1,2,3,1,2,3]
取决于你对工作的定义。
原型扩展有三个主要问题。
- 如果你添加可枚举的属性,它在中打破
- 代码很容易阅读,这是ES5功能还是自定义库?
它将像在 Array.prototype
和 Array
中一样工作,因此您可以添加代码并调用属性。
但是:
Array.prototype.trolls = 42;
for(var k in []){
alert(k ===trolls);
}
上面是一个破坏的例子。 。in
。这很容易用
Object.defineProperty(Array.prototype,trolls,{
value:.. 。,
enumerable:false
});
(仅限ES5。在旧版引擎中无法模拟IE
或与
for(var k in []){
if([] .hasOwnProperty(k)){
alert(k ===trolls);
}
}
个人我避免自动扩展本地人因为这些确切的原因。但我认为在你的库中有 .extendNatives
函数是完全可以接受的,例如
Can I safely extend Javascript builtin classes, like Array
?
I.e. on which browsers/environments will the following not work:
Array.prototype.double = function() { return this.concat(this); }
Array.twice = function(a) { return a.double(); }
Array.twice([1, 2, 3]) # => [1, 2, 3, 1, 2, 3]
Depends on your definition of "work".
There are three main issues with prototype extension.
- it's global scope so there is name collision
- If your adding enumerable properties it breaks
for .. in
- Code is confusing to read, is this an ES5 feature or a custom library?
It will work as in, Array.prototype
and Array
are mutable so you can add the code and call the properties.
However:
Array.prototype.trolls = 42;
for (var k in []) {
alert(k === "trolls");
}
The above is an example of it breaking for .. in
. This is easily solved with
Object.defineProperty(Array.prototype, "trolls", {
value: ...,
enumerable: false
});
(ES5 only. Breaks in IE<9. can't be emulated in legacy engines)
or with
for (var k in []) {
if ([].hasOwnProperty(k)) {
alert(k === "trolls");
}
}
Personally I avoid automatically extending natives for these exact reasons. However I think it's perfectly acceptable to have a .extendNatives
function in your library like pd.extendNatives
这篇关于我可以安全地扩展javascript内置类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!