Created
February 22, 2016 13:48
-
-
Save deepakkj/b7e5a671475e68995b5e to your computer and use it in GitHub Desktop.
Methods are bound to an object as a property : Invoking methods which are 'out-of-context'
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//creating a class named Person with a constructor | |
var Person = function(firstName){ | |
this.firstName = firstName; | |
}; | |
//creating prototpye function to access it, with multiple objects while it is loaded only once in memory | |
Person.prototype.sayHello = function(){ | |
console.log("My name is " + this.firstName); | |
}; | |
//creating two objects from the class Person with inital names | |
var p1 = new Person("Deepak"); | |
var p2 = new Person("Harman"); | |
//calling the method and assigning it to helloFunction | |
//sayHello doesnt have a closing brackets, since this variable is created just to test its working | |
var helloFunction = p1.sayHello; | |
//printing the respective names | |
p1.sayHello(); //logs "My name is Deepak" | |
p2.sayHello(); //logs "My name is Harman" | |
//testing | |
console.log(helloFunction === p1.sayHello); //logs true | |
///testing again | |
console.log(helloFunction === Person.prototype.sayHello); //logs false | |
//testing again | |
helloFunction(); //logs error, since there is no object to which it can reference it to. | |
//testing again | |
helloFunction.call(p1); //logs "My name is Deepak" , since it can now reference to the object named p1. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment