What is meant by “public function can't be overridden if a patch is necessary.” in Addy's description of the Revealing Module Pattern?

怎甘沉沦 提交于 2019-11-26 22:54:16

Compare an object created by using an object literal to one created by the Revealing Module Pattern.

Here is one created as an object literal.

function makeGreeter(name){
  return {
    getName: function(){ return name;},
    sayHello: function(){console.log("Hello, " + this.getName());}
  }
}

var greeter = makeGreeter("Danny");
greeter.sayHello; // "Hello, Danny"
greeter.getName = function(){ return "George";}
greeter.sayHello(); // "Hello, George"

When you override the public method getName on the returned object, the sayHello method which depends on getName picks up the change. This is because in the Object Literal style, references to public functions are made via this, the returned object.

However, when you use the Revealing Module Pattern,

function makeGreeter(name){
  var getName = function(){ return name;},
    sayHello = function(){console.log("Hello, " + getName());};
  return {
    getName: getName,
    sayHello: sayHello
  }
}

var greeter = makeGreeter("Danny");
greeter.sayHello; // "Hello, Danny"
greeter.getName = function(){ return "George";}
greeter.sayHello(); // "Hello, Danny"

The RMP greeter will not pick up the override to the public getName method. This is because when RMP functions reference other functions (both public and private), they refer to the private closure copy rather than to the public function attached to the returned object.

It is for this reason I regard the Revealing Module Pattern as an anti-pattern.

Sumi Straessle

I would bind getName to this, which, it seems, points to the content returned in RMP.

function makeGreeter(name){
    this.getName = function(){ return name;};
    var _sayHello = function(){console.log("Hello, " + this.getName());};
    return {
            getName: getName,
            sayHello: _sayHello
    }
}

I prefer this, though:

function makeGreeter(name){
    this.getName = function(){ return name;};
    var _sayHello = function(){console.log("Hello, " + this.getName());};
    var API = {
        getName: getName,
        sayHello: _sayHello
    };
    return API;
}
neo19

The answer given by @I-Lin Kuo looks good, but for one case creates the confusion.

function makeGreeter(name) {
return {
    getName: function() {
        return name;
    },
    sayHello: function() {
        console.log("Hello," + this.getName());
    }
  }
}

var greeter = makeGreeter("Danny");
greeter.sayHello(); //"Hello,Danny"
greeter.getName = function() {
    return "George";
}
greeter.sayHello(); //"Hello,George"

Instead of greeter.sayHello it should have been greeter.sayHello(). Creates a lot of confusion.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!