[英]Javascript constructor function return this
I'm used to a javascript object constructors looking like this 我习惯了像这样的javascript对象构造函数
function person(first, last) {
this.firstName = first;
this.lastName = last;
}
var dude = new person("the", "dude");
But sometimes I see the constructor return "this", like so 但是有时候我看到构造函数返回“ this”,就像这样
function person(first, last) {
this.firstName = first;
this.lastName = last;
return this;
}
What's up with returning this
at the end? 最后返回
this
是怎么回事?
There's no point in returning this
from a constructor, but you are allowed to return any object you'd like. 从构造函数返回
this
没有任何意义,但是您可以返回任何想要的对象。 If no object is explicitly returned, this
is implicitly returned. 如果明确返回任何对象,
this
是隐式返回。
A possible use case is: 一个可能的用例是:
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);
The only case that I know it could mean something is if you instantiate your objects in the following manner; 我知道这可能意味着某件事的唯一情况是,如果您以以下方式实例化对象;
person.call(Object.create(person.prototype), 'Jack', 'Brown');
The above example requires that you return this
; 上面的示例要求您返回
this
;
What can be done, but should be avoided, is to return a different object than 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.