3

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

javascript是这样的吗?

.

举个例子...

就我而言,我想更改 Google Apps 脚本处理 URL 对象的方式,以便每次评估 URL 对象时,URL 对象本身都会确保它以协议 ://(默认为 http://)开头。

4

4 回答 4

3

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

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;
    }());
}());
于 2013-06-26T21:03:00.593 回答
2

Yes.

With the caveat that how you define a "class" is pretty different than in Ruby. But you can achieve the same effect.

This ruby:

#ruby
class Foo
  # no methods yet
end

foo = Foo.new

class Foo
  def bar
    'bar'
  end
end

foo.bar #=> 'bar'

Would have this equivalent JavaScript implementation:

// js
var Foo = function() {};

var foo = new Foo();

Foo.prototype.bar = function() {
  return 'bar';
};

foo.bar(); // 'bar'

You can even override things just as easily:

var oldBar = Foo.prototype.bar;
Foo.prototype.bar = function() {
  return "Called oldBar and got: "+ oldBar.call(this);
};

foo.bar(); // "Called oldBar and got: bar"
于 2013-06-26T21:01:39.880 回答
1

您在问题中特别提到了 Google Apps 脚本。由于 GAS 是JavaScript 的变体,因此适用对象定义和扩展的“常用方法”,如其他答案所述。

但是,有一个非常烦人的例外:您不能扩展 Google 类的原型。您可以在问题跟踪器Issue 708上找到有关此问题的评论。它被标记为“不会修复”。

于 2013-09-10T16:52:19.267 回答
1

see this class with getter and setter:

function User(){
this._name = "";
}
User.prototype.setName = function(name){this._name = name;}
User.prototype.getName = function(){return this._name;}
user = new User();
user.setName("somename");
alert(user.getName(););

JSfiddle Example

于 2013-06-26T21:02:48.407 回答