[英]Javascript constructor function return this
我習慣了像這樣的javascript對象構造函數
function person(first, last) {
this.firstName = first;
this.lastName = last;
}
var dude = new person("the", "dude");
但是有時候我看到構造函數返回“ this”,就像這樣
function person(first, last) {
this.firstName = first;
this.lastName = last;
return this;
}
最后返回this
是怎么回事?
從構造函數返回this
沒有任何意義,但是您可以返回任何想要的對象。 如果明確返回任何對象, this
是隱式返回。
一個可能的用例是:
function person(first, last) { if(!(this instanceof person)) { return new person(first, last); } this.first = first; this.last = last; } var person1 = new person('first', 'person'); var person2 = person('second', 'person'); // <- without "new" console.log(person1, person2);
我知道這可能意味着某件事的唯一情況是,如果您以以下方式實例化對象;
person.call(Object.create(person.prototype), 'Jack', 'Brown');
上面的示例要求您返回this
;
可以做但應該避免的是返回一個與this
不同的對象
function person(first, last) {
return {first: first, last: last};
}
(new Person() ) instanceof Person // false
返回this
值,以便呼叫者可以將呼叫鏈接在一起。
console.log(new person('First', 'Last').firstName);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.