Understanding the superior method introduced by Crockford

后端 未结 4 574
日久生厌
日久生厌 2020-12-18 09:23

In the functional inheritance pattern, Crockford introduces a new superior method via:

Object.method(\'superior\', function (name) {
    var th         


        
4条回答
  •  别那么骄傲
    2020-12-18 09:45

    "My question is Why don't just assign that.get_name to super_get_name?"

    Because the way the get_name method has its this value set to the that object is by invoking it as:

    that.get_name();
    

    When a function is invoked as the method of an object, the object becomes the value of this in that invocation of the function.

    If you had done this instead:

    var super_get_name = that.get_name;
    
    super_get_name();
    

    Now you're invoking a detached function, so it doesn't know what its this value should be, and so it uses the default, which is usually the window object.


    I don't like the solution that crockford shows at all. Typically, in that situation, you'd simply make a new function right there instead of relying on extensions to Object.prototype to do it for you. (Extending Object.prototype is very ugly IMO.)

    var coolcat = function (spec) {
        var that = cat(spec),
            _original_get_name = that.get_name,
            super_get_name = function() {
                                 return _original_get_name.apply(that, arguments);
                             };
    
        that.get_name = function (n) {
            return 'like ' + super_get_name() + ' baby';
        };
        return that;
    };
    

    Or in modern implementations, you'd use Function.prototype.bind to create a new function with its this value bound to whatever you provided as the first argument to .bind().

    var coolcat = function (spec) {
        var that = cat(spec),
            super_get_name = that.get_name.bind(that);
    
        that.get_name = function (n) {
            return 'like ' + super_get_name() + ' baby';
        };
        return that;
    };
    

提交回复
热议问题