Function call() Method

/ Published in: JavaScript
Save to your folder(s)

This method allows you to call a function as a method of another object. The first argument the call method expects is the object it is to operate on. Any others are part of the function. Note how the this keyword now refers to the comp object, so a result property is created inside comp.

Copy this code and paste it in your HTML
  1. function containerScope(){
  2. var comp = { //create a new object
  3. a: 22, //set some properties
  4. b: 33
  5. };
  6. function square(x){ //create a new function
  7. this.result = x*x;//this refers to the object when used in call()
  8. }
  9., 4); //call the square function as a method of comp object
  10. console.dir(comp); //note how a comp.result property has now been created
  11. }

Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.