First declare your objects
1 2 3 4 5 6 7 8 9 |
Person1 = { name: "gary", age: 25 }; Person2 = { name: "ricky", age: 35 }; |
Then you declare a function…
1 2 3 |
displayName = function() { console.log("name is: " + this.name + ", age is: " + this.age); } |
You can literally attach functions to objects like so:
1 2 3 |
//attach function definition for test, that is attribute of myapp Person1.showName = displayName; Person2.whatsMyName = displayName; |
Where the function uses ‘this’ to access the calling object’s attributes.
Using them like this:
1 2 |
Person1.showName(); Person2.whatsMyName(); |
would give:
name is: gary, age is: 25
name is: ricky, age is: 35