creating objects from JS closure: should i use the “new” keyword?

前端 未结 2 990
别跟我提以往
别跟我提以往 2020-12-01 14:50

i answered one question about closures here in SO with this sample:

function Constructor() {
    var privateProperty = \'private\';
    var privateMethod = f         


        
2条回答
  •  感动是毒
    2020-12-01 15:27

    No, it's not the same thing. Consider when using instanceof:

    function C1() {
        return {};
    }
    
    function C2() {
    }
    
    var c1 = new C1();
    var c2 = new C2();
    alert(c1 instanceof C1); // false; wha...?
    alert(c2 instanceof C2); // true, as you'd expect.
    

    Here's a demo.

    So instead, create them by assigning to this, possibly with a safeguard to prevent forgotten news.

    function Constructor() {
        var privateProperty = 'private';
        var privateMethod = function() {
            alert('Called from private method');
        };
    
        this.publicProperty = "I'm public!";
        this.publicMethod = function() {
            alert('Called from public method');
        };
        this.getter = privateMethod;
    }
    

    Even better, use the prototype when possible:

    function Constructor() {
        var privateProperty = 'private';
        var privateMethod = function() {
            alert('Called from private method');
        };
    
        this.getter = privateMethod;
    }
    
    Constructor.prototype.publicProperty = "I'm public!";
    Constructor.prototype.publicMethod = function() {
        alert('Called from public method');
    };
    

提交回复
热议问题