Reputation: 51
Can you help me to understand ES6 and Object ?
class Contact{
constructor(name,tel,mail)
this.name=name;
this.tel=tel;
this.mail=mail;
method1(){
//code
}
}
If I want create a contact I can use
const me = new Contact('David','070809112','10 street of Paris')
But I'm not able to use Object.create() before ES6 I can use Object.create() with ES6 Ican't can you help me ?
var Contact ={
init:function('name','tel','mail')
this.name=name;
this.tel=tel;
this.mail=mail;
method1 : function(){
//code
}
}
var me = Object.create(Contact);
me.init('David','070809112','10 street of Paris');
In this case How use Object.create() ? for create a new contact. Thanks
Upvotes: 1
Views: 732
Reputation: 49
T.J Crowder answer is the best thing i have ever seen. yeap Reflect.construct() works as expected this has saved my day of hours searching because i had a problem i wanted to call a function with an instance together with other variables off the back in laravel blade, however adding a space in between made the dumb thing break so i could not use the new keyword. javascript flexibility saved the day. Learnt a totally new thing and thank you for being oblivious of why one would not want to use new keyword and focusing on answering the question. i wish i could comment on his answer but low rep.
i had this
onclick={{$var1.".method( new MyClass(this.id,'".$var2."','".$var3."') )"}}
another reason i at times hate templating engines, they can be limiting
Upvotes: 0
Reputation: 1075805
You can keep doing exactly what you were doing and not use class
.
If you're using class
, you typically don't use Object.create
. The use cases for Object.create
are largely unrelated to class
(it's usually used in direct prototypical inheritance, rather than using constructor functions).
If you want to use class
but don't want to use new
for some reason, you can use Reflect.construct
(rather than Object.create
):
class Contact {
constructor(name, tel, mail) {
this.name=name;
this.tel=tel;
this.mail=mail;
}
method1(){
//code
}
}
const c = Reflect.construct(Contact, ["name", "tel", "mail"]);
console.log(c.name);
It is possible to use Object.create
with your class Contact
, like this:
// NOT A GOOD IDEA, see below
const c = Object.create(Contact.prototype);
That creates an object using Contact.prototype
as its prototype. But it doesn't call the constructor, and you can't call the constructor afterward (Contact.call(c, "name", "tel", "email")
would fail). And you couldn't be sure that not calling the constructor didn't cause a problem, since class
code assumes the constructor (and super constructors if any) are called.
Upvotes: 4