Skip to content

Instantly share code, notes, and snippets.

@mitsuru793
Created December 2, 2015 04:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mitsuru793/c4fade127cb4936d2fd7 to your computer and use it in GitHub Desktop.
Save mitsuru793/c4fade127cb4936d2fd7 to your computer and use it in GitHub Desktop.
JavaScriptで、newを使った時の戻り値
// console.logのエイリアス
var l = function(x) { console.log(x) };
function Person(name) {
this.name = name;
}
function PersonWithReturnOther(name) {
this.name = name;
return {age: 13};
}
// newをつけると、自動でthisの値を戻り値として返してくれます。
// newは、functionを実行する前にオブジェクトを生成します。
// 前もって生成したオブジェクトを、funcitonのthisと結びつけます。
l(Person("田中")); // undefined
l(new Person("鈴木")); // Person { name: '鈴木' }
// 明示的にreturnでオブジェクトを指定すると、thisは返りません。
l(PersonWithReturnOther("佐藤")); // { age: 13 }
l(new PersonWithReturnOther("清水")); // { age: 13 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment