+ 1

Same property name for different obj

If I have a few objects with the same property "age" then how JS know which I mean here???: function yearBorn(){ return 2016-this.age; }

6th Nov 2016, 9:30 AM
Eugene Lavrinenko
Eugene  Lavrinenko - avatar
2 odpowiedzi
+ 1
"this" represents your actual object. This code is most likely inside a function in which you iterate through multiple objects, I guess. Or maybe it's in the object definition, in which case it will take the "age" of the object you will then create.
6th Nov 2016, 9:36 AM
Pierre Varlez
Pierre Varlez - avatar
+ 1
I try and what I know: - If a few objects have same property "age" and function "yearBorn()", then calling that function works for all these objects. - If first object has property and function/method and second one has only property, then calling function works only for first object. Excellent! You can try this code to test: function person(name,age){ this.name=name; this.age=age; this.yearOfBirth=yearBorn; } function monster(name,age){ this.name=name; this.age=age; // this.yearOfBirth=yearBorn; } function yearBorn(){ return 2016-this.age; } var p1 = new person("Hero",33); var m1 = new monster("ArchLich",500); yearBorn(); document.write(p1.name," is ",p1.age," y.o.<br/> He was born in ",p1.yearOfBirth()," year.<br/>"); document.write(m1.name," is ",m1.age," y.o.<br/>"); /*document.write(m1.name," is ",m1.age," y.o.<br/> He was born in ",m1.yearOfBirth()," year.<br/>");*/
6th Nov 2016, 9:47 AM
Eugene Lavrinenko
Eugene  Lavrinenko - avatar