最终代码受, answer 和answer 启发:elclanrs
answer
this
this
(function(window) {
var private = {
name: 'John'
};
function foo() {
// if without `new` foo().change() will not work :(
// but foo.change() will
if (!(this instanceof foo))
return new foo();
return this;
}
foo.change = function(key, val) {
private[key] = val;
foo.say();
return this;
};
foo.say = function() {
console.log('Hello '+ private.name);
return this;
}; // prototype used for foo().say() and foo().change()
foo.prototype.change = function(key, val) {
return foo.change(key, val);
};
foo.prototype.say = function() {
return foo.say();
};
window.foo = foo;
})(window);
foo.say().change('name', 'Ben');
// => "Hello John" => "Hello Ben"
foo().change('name', 'Mike').change('name', 'Sam');
// => "Hello Mike" => "Hello Sam"
jsfiddle.net