Rajesh
Rajesh

Reputation: 556

Create variable like "new" in javascript

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

Answers (3)

SciFiThief
SciFiThief

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:

  1. A new object is created, inheriting from Foo.prototype.
  2. The constructor function Foo is called with the specified arguments and this bound to the newly created object. new Foo is equivalent to new Foo(), i.e. if no argument list is specified, Foo is called without arguments.
  3. The object returned by the constructor function becomes the result of the whole new expression. If the constructor function doesn't explicitly return an object, the object created in step 1 is used instead. (Normally constructors don't return a value, but they can choose to do so if they want to override the normal object creation process.)

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:

http://jsfiddle.net/hp244jn7/

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

giorgio
giorgio

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

suvroc
suvroc

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

Related Questions