Javascript constructor - effects of the returned JSON object

Are there any functional differences in performance or functionality between the fact that the javascript constructor returns a literal of a JavaScript object, rather than just setting properties using this.XYZ . For instance:

  function PersonA(fname, lname) { this.fname = fname; this.lname = lname; } function PersonB(fname, lname) { return { "fname": fname, "lname": lname }; } 

Both seem to behave accordingly:

  PersonA.prototype.fullName = function() { return this.fname + " " + this.lname; }; PersonB.prototype.fullName = function() { return this.fname + " " + this.lname; }; var pA = new PersonA("Bob", "Smith"); var pB = new PersonB("James", "Smith"); alert(pA.fullName()); alert(pB.fullName()); 

Is it preferable for any reason, or is it a matter of taste? If the taste is another standard?

+4
source share
2 answers

They are not exactly identical.

If you return an object created from the constructor ...

  • it inherits from the prototype constructor
  • it will have instanceof , available as a testing tool, which constructor created it

The reason the fullName() method works for pB is because you are using the PersonA constructor for both.

 var pA = new PersonA("Bob", "Smith"); // uses PersonA constructor var pB = new PersonA("James", "Smith"); // uses PersonA constructor??? 

FYI, the correct term is "JavaScript object literal", not "JSON object literal".


EDIT:. You updated the code in the question to use the PersonB constructor. Run it again and you will find an error in the console.

+4
source

When you are a new function constructor, an empty object is created and then refers to this inside the function constructor.

So, PersonA , think of it this way:

 // create an empty object var emptyObj = {}; // call the function as a method of the empty object PersonA.call(emptyObj, "Bob", "Smith"); 

The result is emptyObj :

 { fname : "Bob", lname : "Smith" } 

When you call PersonB , you still create an empty object, calling a new one , but essentially doing nothing with it, and return another object to it.

+1
source

Source: https://habr.com/ru/post/1369194/


All Articles