Reputation: 556
Im new to javascript ; and im digging into 'new' variable.
My qustion is :
function Fruit(name)
{
this.name = name;
}
function myNew(con,args){
var obj = {};
obj = con.apply(obj,args) || obj;
obj.constructor = con;
return obj;
}
var f1 = new Fruit("Mango");
var f2 = myNew(Fruit,["Orange"]);
console.log(f1.name, f1 instanceof Fruit);
console.log(f2.name, f2 instanceof Fruit);
now the output im getting is :
Mango true
Orange false
what I need to do if I need output : Mango true Orange true..
I need some explanation here.
I dont know if somebody already answered this question but i was unable to find it.
Upvotes: 0
Views: 56
Reputation: 586
Lets say we have Foo constructor.
function Foo(options) {
// constructor
this.name = options.name;
}
// and create instance of it
var foo = new Foo({name: "Foo"});
From the MDN reference, "new" operator does:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new
So basically it setups object prototype and executes constructor function, returning an object, unless constructor doesn't return anything else.
"apply" function instend, only runs function in specific context. It doesn't setup inheritance. In you case it just runs constructor in context of your custom obj.
var obj = {};
You can see this on this fiddle:
There "_ proto _" property used, to see whats in prototype chain. Don't use it in development.
If you want the desired effect you should probably use what giorgio suggested.
Upvotes: 2
Reputation: 10202
You're thinking to difficult ;) This is doing what you want:
function myNew(con, args) {
return new con(args);
}
see the demo here
Upvotes: 1
Reputation: 3062
You should use prototype property to define that your object is based on some other object
function myNew(con,args){
var obj = {};
obj = con.apply(obj,args) || obj;
obj.prototype = con;
return obj;
}
Upvotes: 1