2

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?

Sampson
  • 265,109
  • 74
  • 539
  • 565
Lok Jun
  • 1,315
  • 2
  • 9
  • 16

3 Answers3

4

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:

enter image description here

Sampson
  • 265,109
  • 74
  • 539
  • 565
3

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);
Durgesh
  • 406
  • 4
  • 8
1

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.

sabof
  • 8,062
  • 4
  • 28
  • 52