What are the downsides of defining functions on prototype this way?

前端 未结 4 636
死守一世寂寞
死守一世寂寞 2020-12-18 10:06

Usually people write code like this:

function Shape() {
  this.x = 0;
  this.y = 0;
}

Shape.prototype.move = function(x, y) {
  this.x += x;
  this.y += y;
         


        
4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-18 10:31

    First off, you state that "the function will only be defined once", however, this is not true AFAIK. Every time you construct a new Shape, the anonymous function

    function(x,y) { this.x += x; this.y += y }
    

    get's redefined (unless the compiler/interpreter is smart enough to optimize this away as it isn't used). It then get's passed to the method Object.prototype.method, which chooses to ignore it (becuase the method was already defined), and is simply left in memory to be garbage-collected. Running this in a loop (if the compiler/interpreter isn't able to optimize it away), would result in a lot of functions being created for no good reason.

    Also, as Johan stated, littering in Object.prototype may cause other code to stop working because suddenly for(x in anything) will show your new function method.

    If you would like to "group" the declaration of the constructor, and it's methods together, you could rather create something like this:

    function mangle(ctor, methods) {
        for(x in methods) {
            if(methods.hasOwnProperty(x)) {
                ctor.prototype[x] = methods[x];
            }
        }
        return ctor;
    }
    

    which you'd then call like this:

    var Shape = mangle(function() {
        // moved default-values to prototype
        // so they don't have to be created
        // if they aren't set to something
        // else than the default.
    }, {
        x: 0,
        y: 0,
        move: function(x, y) {
            this.x += x;
            this.y += y;
        }
    });
    

    Or you could just stick to the normal design, or use a "class"-providing library like Prototype or MooTools. There are a lot of options to choose from.

提交回复
热议问题