Can I construct a JavaScript object without using the new keyword?

后端 未结 15 2766
北海茫月
北海茫月 2020-11-27 16:04

Here is what I\'d like to do:

function a() {
  // ...
}
function b() {
  //  Some magic, return a new object.
}
var c = b();

c instanceof b // -> true
c          


        
15条回答
  •  旧巷少年郎
    2020-11-27 16:46

    Yes. If you don't want to use the 'new' keyword, just use prototype, and return something in your constructor function.

    Using 'new' just tells the constructor functions that:

    1) The 'this' keyword in the constructor function should reference the function itself, not the parent object (as per usual), which would be the window object if this function was declared in the global scope.

    2) For all failed lookups (obj properties not found) on the newly created object/instance, check the original constructor function's prototype property.

    So with new:

        function Point(x, y) {
           this.x = x;
           this.y = y;
        }
        Point.prototype.getDistance = function(otherPoint){
           var Dx = (this.x - otherPoint.x) ** 2;
           var Dy = (this.y - otherPoint.y) ** 2;
           var d = Dx + Dy;
           d = Math.sqrt(d);
           return d
        }
        var pointA = new Point(3, 6);
        var pointB = new Point(5, 8);
        var distanceAB = pointA.getDistance(pointB);
    

    Without new:

        function Point(x, y) {
           let d = Object.create(Point.prototype);
           this.x = x;
           this.y = y;
           return d
        }
        Point.prototype.getDistance = function(otherPoint){
           var Dx = (this.x - otherPoint.x) ** 2;
           var Dy = (this.y - otherPoint.y) ** 2;
           var d = Dx + Dy;
           d = Math.sqrt(d);
           return d
        }
        var pointA = Point(3, 6);
        var pointB = Point(5, 8);
        var distanceAB = pointA.getDistance(pointB);
    

    Try adding removing the 'new' in the the first example, and you'll see the 'this', no longer refers to the constructor function, but the window object instead. You'll be giving your window x and y properties, which proplably isn't what you want.

提交回复
热议问题