简体   繁体   English

JavaScript构造函数返回

[英]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.

相关问题 Javascript 构造函数返回值和 function - Javascript Constructor return value and function Javascript函数(构造函数)返回类型中的奇怪行为 - Javascript strange behavior in function (constructor) return types 在JavaScript中,“返回”在函数构造函数中起什么作用 - In JavaScript, what does “return” do in function constructor JavaScript构造函数可以返回函数并保持继承吗? - Can JavaScript constructor return function and keep inheritance? 构造函数调用一个成员函数,在javascript中返回一个值 - constructor call a member function that return a value in javascript 如何从JavaScript中的构造函数返回字符串? - how to return string from constructor function in javascript? 当返回另一个构造函数时,此值从Javascript构造函数返回 - Return value of this from Javascript constructor function, when another constructor is returned 如何在 ZDE9B9ED78D7E2E911DCEEFFEE780Z 中的当前 function 上返回 function 构造函数 object 属性? - How to return function constructor object property on the current function in javascript? JavaScript构造函数中的return语句 - Return statement in JavaScript constructor 如何从JavaScript中的自定义对象构造函数返回视频时长? - How to return video duration from custom object constructor function in javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM