0

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.

3
  • var newObj = {}..? And check for this inside the function to differentiate. Commented May 17, 2016 at 7:40
  • will not it break when you use the new createObj()? Commented May 17, 2016 at 7:42
  • Check Object.create() and instanceOf operator Commented May 17, 2016 at 7:43

4 Answers 4

1

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 ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

This is a very nice solution!
0

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.

Comments

0

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);

2 Comments

btw if You need such a function ... there must be really bigger and much scary problems in Your code
This function returns a string "BruceLee" (and not an object) when used without the new keyword
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.