Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

4. Function() > Invoking a Function [Function, Method, Constructor, or call() a...

Invoking a Function [Function, Method, Constructor, or call() and apply()]

Functions are invoked using four different scenarios or patterns:

  • As a function

  • As a method

  • As a constructor

  • Using apply() or call()

In the code below, we examine each of these invocation patterns.

Live Code

<!DOCTYPE html><html lang="en"><body><script>

// function pattern
var myFunction = function(){return 'foo'};
console.log(myFunction()); // log 'foo'

// method pattern
var myObject = {myFunction: function(){return 'bar';}}
console.log(myObject.myFunction()); // log 'bar'

// constructor pattern
var Cody = function(){
   this.living = true;
   this.age = 33;
   this.gender = 'male';
   this.getGender = function() {return this.gender;};
}
var cody = new Cody(); // invoke via Cody constructor
console.log(cody); // logs cody object and properties

// apply() and call() pattern
var greet = {
   runGreet: function(){
       console.log(this.name,arguments[0],arguments[1]);
   }
}

var cody = {name:'cody'};
var lisa = {name:'lisa'};

// invoke the runGreet function as if it were inside of the cody object
      greet.runGreet.call(cody,'foo','bar'); // logs 'cody foo bar'

// invoke the runGreet function as if it were inside of the lisa object
      greet.runGreet.apply(lisa, ['foo','bar']); // logs 'lisa foo bar'

/* Notice the difference between call() and apply() in how parameters are sent 
to the function being invoked */

</script></body></html>

  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint