最終更新:2021-02-25 (木) 23:32:44 (1148d)
JavaScript/オブジェクト指向
Top / JavaScript / オブジェクト指向
キーワード
JavaScript/this
- 呼び出し元によって参照先のオブジェクトが変化する
- Function.prototype.call
JavaScript/new
JavaScript/prototype
JavaScript/モジュール化
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 () { // ... } };