将javascript构造函数包装到另一个函数中

时间:2022-01-23 20:35:12

I have a function for creating objects as follows:

我有一个创建对象的功能,如下所示:

function person() {
    this.name = "test person";
}
var me = new person();

Now I'm planning to wrap this function into another one like this for assertion purposes.

现在我打算将这个函数包装成另一个这样的函数用于断言目的。

function reliable_person() {
    /* do check on params if any*/
    return new person();
}
var me = new reliable_person();

Is this a possible approach? I know there are better ways for such checks within the constructor itself, but is this a reliable solution?

这可能是一种方法吗?我知道在构造函数本身中有更好的方法进行此类检查,但这是一个可靠的解决方案吗?

1 个解决方案

#1


2  

Invoking a function with new constructs a new object and uses the given function to initialise the object. Something that's a bit special about this is that if you return a non-primitive value, like an object, from that function, that value will be used as the new object instead. Sounds complicated, but what it boils down to is that reliable_person() and new reliable_person() result in the exact same thing, because you're returning an object from it. So using new with that function is pointless.

使用new调用函数构造一个新对象并使用给定函数初始化该对象。对此有点特别的是,如果从该函数返回非原始值(如对象),则该值将用作新对象。听起来很复杂,但它归结为warm_person()和new reliable_person()导致完全相同的事情,因为你从它返回一个对象。所以使用new函数是没有意义的。

Removing the superfluous new from it, all that's left is a normal function which returns an object (a "factory function"). Yes, that works and is "reliable".

从中删除多余的新东西,剩下的只是一个返回对象的常规函数​​(“工厂函数”)。是的,这有效并且“可靠”。

#1


2  

Invoking a function with new constructs a new object and uses the given function to initialise the object. Something that's a bit special about this is that if you return a non-primitive value, like an object, from that function, that value will be used as the new object instead. Sounds complicated, but what it boils down to is that reliable_person() and new reliable_person() result in the exact same thing, because you're returning an object from it. So using new with that function is pointless.

使用new调用函数构造一个新对象并使用给定函数初始化该对象。对此有点特别的是,如果从该函数返回非原始值(如对象),则该值将用作新对象。听起来很复杂,但它归结为warm_person()和new reliable_person()导致完全相同的事情,因为你从它返回一个对象。所以使用new函数是没有意义的。

Removing the superfluous new from it, all that's left is a normal function which returns an object (a "factory function"). Yes, that works and is "reliable".

从中删除多余的新东西,剩下的只是一个返回对象的常规函数​​(“工厂函数”)。是的,这有效并且“可靠”。