+ 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?
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();
+ 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.
0
well explained
0
Good explanation