简体   繁体   中英

Javascript method chaining definition

What is the difference between when using method chaining in Javascript I know that this can have some strange quirks so I am unsure:

var Kitten = function() {
  this.name = 'Garfield';
  this.color = 'brown';
  this.gender = 'male';
};

Kitten.prototype.setName = function(name) {
  this.name = name;
  return this;
};

Kitten.prototype.setColor = function(color) {
  this.color = color;
  return this;
};

var obj = new Kitten().setName("tom").setColor("red");

And

var Kitten = function() {
  this.name = 'Garfield';
  this.color = 'brown';
  this.gender = 'male';
  this.setColor = function(color) {
     this.color = color;
     return this;
  };
  this.setName = function(name) {
     this.name = name;
     return this;
  };

};

var obj = new Kitten().setName("tom").setColor("red");

The outcome is the same in terms of calling the code, the difference between the implementations is this:

When you have the functions called within the instantiating function, they are created every time you create a new object. When they are created on the prototype, then those functions are shared between all instances.

Both have advantages and disadvantages - you can use internal functions to create something like "private" member variables that you might see in other languages and to implement the Module pattern that is widely used among JavaScript developers, but if you are going to be creating a lot of objects then having shared prototype functions can be a lot more memory efficient. People don't think much about memory efficiency these days, but if you are targeting mobile platforms it can be relevant.

I prefer to use prototypes because it feels to me as though it goes more naturally with the flow of the language but- as with all serious JavaScript development - it does mean that sometimes you end up in baffling scoping scenarios.

There's no difference.

When you use this inside an object you are putting values into object.

You automatically add name property into Kitten object:

var Kitten = function() {
    this.name = 'Garfield';
}

You explicitly add name into Kitten prototype from outside:

 var Kitten = function() {
 }

 Kitten.prototype.name = "Garfield";

Prototype is shared between objects when you use new Kitten() and what was created inside the function with this will be re-created.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM