Created
December 2, 2015 04:45
-
-
Save mitsuru793/c4fade127cb4936d2fd7 to your computer and use it in GitHub Desktop.
JavaScriptで、newを使った時の戻り値
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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