我正在尝试以这种方式扩展对象功能:
Object.prototype.get_type = function() {
if(this.constructor) {
var r = /\W*function\s+([\w\$]+)\(/;
var match = r.exec(this.constructor.toString());
return match ? match[1].toLowerCase() : undefined;
}
else {
return typeof this;
}
}
很棒,但是有一个问题:
var foo = { 'bar' : 'eggs' };
for(var key in foo) {
alert(key);
}
将有3个周期。
有什么办法可以避免这种情况吗?
一方面,我并不完全反对扩展原生类型,ECMA-262 第 5 版 http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf。以很好的方式为我们解决了其他答案和链接文章中提到的问题。看看这些slides http://davidflanagan.com/Talks/es5/slides.html以获得良好的概览。
您可以扩展任何对象并定义控制这些属性行为的属性描述符。当您访问对象属性时,该属性可以成为不可枚举的含义for..in
循环,该属性将不会被包含在内。
以下是如何定义getType
Object.prototype 本身的方法,并使其不可枚举:
Object.defineProperty(Object.prototype, "getType", {
enumerable: false,
writable: false,
configurable: false,
value: function() {
return typeof this;
}
});
// only logs "foo"
for(var name in { "foo": "bar" }) {
console.log(name);
}
The getType
上面的函数几乎没有什么用,因为它只是返回 typeofobject
在大多数情况下,它只是对象,但它仅用于演示。
[].getType();
{}.getType();
(6).getType();
true.getType();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)