3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Proxy使ってsuperを実装

3
Posted at

メタプログラミングは素晴らしいですね!
demo: http://jsfiddle.net/qGYVd/1/

//実装その1。Python風にsuper
var __super = function(self) {
    return Proxy.create({
        get: function(rcvr, name) {
            return self.__proto__.__proto__[name].bind(self);
        }
    });
};

//その2。this.superで。・・・怒られなかった、いいのか?
Object.defineProperty(Object.prototype, 'super', {
    get: function() {
        var get = function(rcvr, name) {
            return this.__proto__.__proto__[name].bind(this);
        };
        return Proxy.create({get: get.bind(this)});
    }
});

var A = function() {
    this.message = 'world';
};
A.prototype.foo = function() {
    this.print('hello ' + this.message);
};
A.prototype.print = function(text) {
    console.log(text);
};

var B = function() {
    this.message = '世界';
};
B.prototype = new A;
B.prototype.foo = function() {
    __super(this).foo();
    this.super.foo();
    this.print('override!');
};

var a = new A;
a.foo();

var b = new B;
b.foo();
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?