I was wondering if it is possible to do the following:
worker.name("John").salary(100)
Basically, this changes the worker's(John's) salary to 100.
Is there a way to define a function in a function?
Can you tell me the method and explain it?
I was wondering if it is possible to do the following:
worker.name("John").salary(100)
Basically, this changes the worker's(John's) salary to 100.
Is there a way to define a function in a function?
Can you tell me the method and explain it?
This is often times called chaining. Essentially, each method returns the parent object:
var worker = {
name: function ( name ) {
this._name = name;
return this;
},
salary: function ( salary ) {
this._salary = salary;
return this;
}
};
worker.name("Jonathan").salary("$1");
alert( worker._name );
alert( worker._salary );
You'll note that each method returns the object. This is made very clear in the following screenshot. If we console output the results of calling the name method, we see that the entire worker
object is returned:
Create a constructor function like:
var Worker = function(){
};
Worker.prototype.name = function (name){
this.name = name;
return this;
};
Worker.prototype.salary = function (salary){
this.salary = salary;
return this;
}
Now above constructor function can be used as:
var worker = new Worker();
worker.name("John Doe").salary(100);
This is possible:
var worker = {
nameVar: null,
salaryVar: null,
name: function(name) {
this.nameVar = name;
return this;
},
salary: function(salary) {
this.salaryVar = salary;
return this;
}
}
Each method modifies the object, and returns this
, which is the object. Then you can call another method, like in your example, without writing the object name explicitly.
Alternatively, you can implement a .clone
method, and instead of this
, return the clone with a modified property. This would be somewhat similar to the way jQuery
works.