javascript对象是否“打开”?喜欢Ruby? [英] Are javascript objects "open" like Ruby?

查看:68
本文介绍了javascript对象是否“打开”?喜欢Ruby?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Ruby中,我可以使用与声明我自己的语法相同的语法来添加和修改任何类,对象或方法的功能,因为Ruby具有开放类。

In Ruby, I can add and modify functionality of any class, object, or method using the same syntax I would to declare my own because Ruby has "open classes".

是这样的javascript吗?

Is javascript like that?

作为示例......

As an example...

在我的情况下,我想改变Google Apps脚本处理URL对象的方式,这样每次评估URL对象时,URL对象本身都会确保它以协议开头:// (http://默认情况下)。

In my case, I want to change the way Google Apps Script handles URL objects so that every time I evaluate a URL object, the URL object itself makes sure it begins with a protocol :// (http:// by default).

推荐答案

是的,您可以自由修改对象。您可以修改特定对象 Object.overridenProperty = ... ,或通过其类派生的所有对象> prototype property Object.prototype.inheritedMethod = ...

Yes, you can modify objects freely. You can modify a particular object Object.overridenProperty = ..., or modify all objects derived from a given class via its prototype property Object.prototype.inheritedMethod = ....

请注意,重新定义方法可能会很棘手,因为新定义不会与原始定义共享相同的范围:

Have in mind that redefining a method can be tricky, as the new definition won't share the same scope as the original definition:

var BaseClass;

(function(){
    var defaults = { ... };

    BaseClass = function(){
        this.someValue = defaults.someValue;
    };
}());

也可能发生类定义位于闭包内并且你没有实际的方法来覆盖方法或属性,因为它生成JIT。在这种情况下,您需要覆盖您感兴趣的每个对象的属性:

It could also happen that the class definition lies inside a closure and you have no practical way to override a method or property as it is generated JIT. In that case you'd need to override the property at each object you are interested in individually:

(function(){
    var defaults = { ... },
    BaseObject = (function(){
        var obj = function(){
            this.someValue = defaults.someValue;
        };

        return obj;
    }());
}());

这篇关于javascript对象是否“打开”?喜欢Ruby?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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