user3196985
user3196985

Reputation: 7

how to create a object form a function without using a new keyword

i have a function. say function createObj() { }

  1. var obj1= new createObj();
  2. var obj2= createObj();

what changes you need to make in the function createObj() to support both above secenario with and without new keyword. Both should work at the same time.

Upvotes: 0

Views: 90

Answers (4)

Ali Mamedov
Ali Mamedov

Reputation: 5256

I can advice to you to read some books about JavaScript. Object-Oriented JavaScript - Second Edition

And you can use this small example:

function Sample() { // Sample is the constructor function for your objects

    return {

        prop_1: 'value',
        prop_2: 3
    }
}

var obj = Sample(); // without new

console.log(obj); // Object { prop_1="value",  prop_2=3}

var obj = new Sample(); // with new

console.log(obj); // The same result with new operator: Object { prop_1="value",  prop_2=3}

This is possible only if the return value of your constructor is an object

Upvotes: 0

fedeghe
fedeghe

Reputation: 1318

Removed the previous answer cause there is a simpler way


Actually there is a simpler way to do that

function o(n, s) {

  function inner(n, s){
    this.name = n;
    this.surname = s;
  }

  return new inner(n, s);
}

var lee1 = new o('Bruce', 'Lee'),
    lee2 = o('Brandon', 'Lee');
console.log(lee1);
console.log(lee2);

Upvotes: 0

CS.
CS.

Reputation: 786

In the function test the type of this and use the new keyword internally, whenever required

function createObj()
{
   if ( !(this instanceof createObj) )
      return new createObj();

   // add existing code of function createObj here ...
}

Upvotes: 1

slebetman
slebetman

Reputation: 113866

It's a bit hacky and I don't really recommend doing this but I understand the reasons for why it's sometimes necessary if you need to integrate with some legacy code or transition your API. Here's one way of doing it.

First, we need a way to detect if our function is called with new or not. Now, depending on weather we're in strict mode or not, if it's not called with new then this will either be undefined or the global object. If it's called with new then it will be an instance of the object inherited from the prototype. So here's how we can check:

function createObj () {
    if (typeof this == 'undefined' || typeof this.Array == 'function') {
        // Not called with `new`
    }
    else {
        // Called with `new`
    }
}

Now using this we can properly construct the object:

function createObj () {
    var self; // replacement of `this` because what it points to
              // depends on the logic below:

    if (typeof this == 'undefined' || typeof this.Array == 'function') {
        // Not called with `new`
        self = Object.create(createObj.prototype); // create object instance
    }
    else {
        // Called with `new`
        self = this;
    }

    // From this point on do things normally except use `self`
    // instead of `this`..


    // Remember to return `self` at the end for when we are not
    // called with `new`:
    return self;
}

Now the function can be used as either a constructor or object factory.

Upvotes: 0

Related Questions