什么时候应该在JavaScript中使用构造函数?

例如,我有这个构建Car对象的函数.

function Car() {
    var honkCount = 0;
    var honkHorn = function () {
        honkCount++;
        $results.html('HONK!<br />');
    };
    return {
        get honkCount() {
            return honkCount;
        },
        honk: honkHorn
    }
}

var car = new Car();和var car = Car();似乎并没有太大的区别,我有点困惑自己.

最佳答案

Both var car = new Car(); and var car = Car(); don’t seem to make much difference and I’m confusing myself a bit.

你是对的,它们都是一样的,只是因为你从函数中返回一个对象. From the MDN documentation

3. The object returned by the constructor function becomes the result of the whole new expression. If the constructor function doesn’t explicitly return an object, the object created in step 1 is used instead. (Normally constructors don’t return a value, but they can choose to do so if they want to override the normal object creation process.)

正如文档中所说,通常构造函数不会显式返回值.

转载注明原文:什么时候应该在JavaScript中使用构造函数? - 代码日志