3

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".

Is javascript like that?

.

As an example...

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).

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
themirror
  • 9,963
  • 7
  • 46
  • 79

4 Answers4

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;
    }());
}());
Ast Derek
  • 2,739
  • 1
  • 20
  • 28
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"
Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
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

Muath
  • 4,351
  • 12
  • 42
  • 69
1

You've specifically mentioned Google Apps Script in your question. Since GAS is a variant of JavaScript, the "usual methods" of object definition and extension apply, as covered in the other answers.

However, there's one terribly annoying exception: You cannot extend prototypes of Google's Classes. You can find comments about this on the issue tracker, Issue 708. It's been marked "Won't Fix".

Community
  • 1
  • 1
Mogsdad
  • 44,709
  • 21
  • 151
  • 275