最終更新:2020-06-05 (金) 01:15:34 (29d)  

JavaScript/オブジェクト指向
Top / JavaScript / オブジェクト指向

キーワード

JavaScript/this

JavaScript/new

  • newをつけて関数を呼び出すとthisが生成されたオブジェクトに夏

JavaScript/prototype

書き方

JavaScript/モジュールパターン

  • Private members live in the closure.
  • Public members are exposed in the return object.
  • 匿名関数の中で関数を定義するだけだと外からアクセスできないのでreturnする
    myNameSpace = function(){
      var current = null;
      function verify(){...}
      return{
        verify:verify
      }
    }();

Revealing Module Pattern

  • the most famous and most popular of the Module Pattern variants.
  • Rename public functions without changing function body.
  • Change members from public to private or vice versa by modifying a single line, without changing the function body.
  • 違い
    • satisfies three additional conditions in addition to those in the original:
  • All members, whether public or private, are defined in the closure.
  • The return object is an object literal with no function definitions. All right hand side expressions are closure variables
  • All references are via the closure variables, not the return object.
  • myNameSpace = function(){
      var current = null;
      function init(){...}
      function change(){...}
      function verify(){...}
      return{
        init:init,
        set:change
      }
    }();

The Module Pattern with Object Literal

  • 変数へのアクセスにthisが必要
    ar welcomeModule = (function(){
      var name: "John";
      var sayHello = function(){ console.log("Hello, " + name + "!");};
      return {
        //name: "John",
        //sayHello: function(){ console.log("Hello, " + this.name + "!");}
        sayWelcome: function() { console.log( hello() + " Welcome to StackOverflow!");}
      }
    })();

The Module Pattern with Return Object Stub

  • var welcomeModule = (function(){
      var stub = {};
      var name = "John";
      var sayHello = function(){ console.log("Hello, " + name + "!");}
    
      stub.sayWelcome = function() { console.log( hello() + " Welcome to StackOverflow!");}
      return stub;
    })();

JavaScript/オブジェクトリテラル記法

  • var myObjectLiteral = {
     
        variableKey: variableValue,
     
        functionKey: function () {
          // ...
        }
    };

関数一個ずつ

prototype使う

関連

参考