如何在不使用 new 关键字的情况下从函数创建对象
how to create a object form a function without using a new keyword
i have a function. say function createObj(( { }
- var obj1= new createObj((;
- 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}
仅当构造函数的返回值是对象时,这才有可能
相关文章:
- 在不使用jquery的情况下查找页面中的所有锚点并附加函数
- 在不破坏未定义函数的情况下,对多个视图使用单个js文件
- 如何在不使用 new 关键字的情况下从函数创建对象
- 在什么情况下需要同时使用compile&链接函数的角度
- 为什么在这种情况下,“This”确实充当javascript函数中的私有成员
- 是否可以在不更改上下文的情况下调用函数.apply
- 如何在不编写样板代码的情况下在Node中创建可重用函数
- 是否可以在没有外部输入的情况下使函数具有自我意识
- 如何在不预定义的情况下将javascript函数传递到另一个函数中
- setTimeout()在忽略间隔的情况下重复调用函数
- 如何在不使用javascript执行的情况下为函数分配参数
- AJAX函数在没有警报的情况下无法工作
- 在没有大量回调函数的情况下在列表元素上循环播放同一动画
- 在不使用隔离作用域的情况下执行函数的角度指令
- 在这种情况下,如何将字符串添加到函数中 php
- 我可以在不编写函数的情况下使用 scrollTop 吗?
- ReactJs:this.setState的情况下不调用回调函数
- 如何在没有javascript中的split函数的情况下将字符串拆分为单词
- 在没有内置 Javascript 函数的情况下将基数 10 转换为其他基数 2 的数字
- 函数在我的情况下无法执行