用JavaScript扩展对象 [英] Extending Object in Javascript

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

问题描述

我正在尝试以这种方式扩展对象功能:

I'm trying to extend Object functionality this way:

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

很好,但是有一个问题:

It's great, but there is a problem:

var foo = { 'bar' : 'eggs' };
for(var key in foo) {
    alert(key);
}

将有3个周期的循环. 有什么办法可以避免这种情况?

There'll be 3 passages of cycle. Is there any way to avoid this?

推荐答案

我并不完全反对扩展本机类型和 ECMA-262第5版.为我们很好地解决了其他答案和链接文章中提到的问题.有关良好的概述,请参见这些幻灯片.

I, for one, am not completely against extending native types and ECMA-262 5th ed. solves the problems mentioned in other answers and linked articles for us in a nice manner. See these slides for a good overview.

您可以扩展任何对象并定义控制那些属性行为的属性描述符.当您在for..in循环中访问对象属性时,可以将该属性设置为不可枚举,该属性将不包括在内.

You can extend any object and define property descriptors that control the behavior of those properties. The property can be made non enumerable meaning when you access the objects properties in a for..in loop, that property will not be included.

这是您可以在Object.prototype本身上定义getType方法并使之不可枚举的方法:

Here's how you can define a getType method on Object.prototype itself, and make it non enumerable:

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

上面的getType函数几乎没有用,因为它只是返回typeof object,在大多数情况下,该类型只是对象,但这仅用于演示.

The getType function above is mostly useless as it simply returns the typeof object which in most cases will simply be object, but it's only there for demonstration.

[].getType();
{}.getType();
(6).getType();
true.getType();

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

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