+ 4

Can i write a function outside an object and associate it with multiple different objects sharing some common property upon which the function operates (turning it to a method for all these objects)? If not , whats the use of defining a method outside the object and assigning it to an object property?

26th Aug 2016, 8:03 PM
Reema Amro
Reema Amro - avatar
4 Réponses
+ 10
Yes, you can. function printName() { document.write("My name is " + this.name) }; var foo = {name: "foo", answer: 42, introduceSelf: printName}; var bar = {name: "bar", question: "6*9", introduceSelf: printName}; foo.introduceSelf(); bar.introduceSelf();
27th Aug 2016, 8:48 AM
Zen
Zen - avatar
+ 1
Yes, you can. Javascript is an OOP language. This means it's possible to create classes. From the classes, we then have our objects as instances of the class. Basically, when you create an object using the constructor method, you're creating a class. Think of a class as a template for our objects. Therefore, any method declared as part of the class, can be accessed by any object of that class. Hope that was helpful.
2nd Feb 2017, 7:24 PM
Jacob Makau
Jacob Makau - avatar
0
well explained
27th Jan 2017, 5:52 PM
Marshial Dominik
Marshial Dominik - avatar
0
Good explanation
8th Feb 2017, 4:28 PM
Ratheesh
Ratheesh - avatar