如何在不使用 new 关键字的情况下从函数创建对象

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

本文关键字:情况下 函数 创建对象 关键字 new      更新时间:2023-09-26

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

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

您需要在函数 createObj(( 中进行哪些更改以支持上述带有和不带有新关键字的 secenario。两者应同时工作。

在函数中测试this的类型,并在需要时在内部使用 new 关键字

function createObj()
{
   if ( !(this instanceof createObj) )
      return new createObj();
   // add existing code of function createObj here ...
}

这有点笨拙,我真的不建议这样做,但我理解为什么如果您需要与一些遗留代码集成或转换 API 有时需要这样做的原因。这是一种方法。

首先,我们需要一种方法来检测我们的函数是否被new调用。现在,根据天气情况,我们是否处于严格模式,如果没有使用 new 调用它,那么this要么是undefined,要么是全局对象。如果使用 new 调用它,那么它将是从原型继承的对象的一个实例。因此,以下是我们可以检查的方法:

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

现在使用它,我们可以正确地构造对象:

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

现在,该函数可以用作构造函数或对象工厂。

删除了之前的答案,因为有一种更简单的方法


实际上有一种更简单的方法可以做到这一点

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

我可以建议你阅读一些关于JavaScript的书。面向对象的 JavaScript - 第二版

你可以使用这个小例子:

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}

仅当构造函数的返回值是对象时,这才有可能