Help us understand the problem. What is going on with this article?

JavaScript で動的オーバーライド時にもとのメソッドを呼び出す方法

More than 5 years have passed since last update.

JavaScriptでオブジェクトのメソッドを実行時に書き換えること自体は簡単ですが、
オーバーライドメソッド内でもとのメソッドを呼び出したい場合はどうすればよいのでしょうか。
このサンプルコードでは、クロージャーを利用することで名前空間を汚染することなくオリジナルのメソッドを保持し、オーバーライド1を実現しています。

var anObject = {
  state: "hoge", 
  getState: function () { return this.state; }
};

anObject.getState(); // "hoge"


anObject.getState = (function () { 
  var context = anObject;
  var original = anObject.getState;
  return function () { return "state: " + original.call(context); };  // override-method
})();

anObject.getState(); // "state: hoge"

(ちなみに黒魔術なので、過度な利用は控えたほうが良いかと思います。。)


1. JSにはクラスの概念が無いですが、「オブジェクトのメソッドを書き換える」ぐらいの意味で使っています

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away