+ 2
What is the difference between these three declaration of object in java script ?
https://code.sololearn.com/WvPEs6P32prt/?ref=app // using object notation var person1={ name:"coder", job:"coding", work:function(){ console.log("code code code..")}}; //using constructor. function person2() { this.name="coder"; this.job="coding" this.work=function(){ console.log("code code code..") } } var ob=new person2(); //using class class person3 { constructor(){ this.name="coder"; this.job="coding"; } work() { console.log("code code code.."); } }
2 odpowiedzi
+ 2
To be precise, the first object person1 is an object entity which stores value in key-value format. And those values can be changed during runtime.
In the second example, person2 is a function, and using new keyword converts a function call to a constructor call.
In the third using class concept, which had been introduced in ES6, we can create a class and it's method and constructors. And like other languages, we can create an object of those class using the new keyword and calling the constructor.
Execution: (work method)
For example 1:
person1.work();
For example 2:
ob.work();
For Example 3:
var obj = new Person3();
obj.work();
Speaking of this keyword, Every function, while executing has a reference to its current execution context called 'this'.
And in class as well 'this' represents the reference to its instance properties.
+ 1
Sami Khan thanks