我开始阅读stampit JS昨日的源代码,并通过调用应用()可变封闭式功能
instance = fn.apply(instance, arguments) || instance;
请问这个真正的工作中发现的封装函数变量的一种有趣的方式在一个对象? 为什么下面的代码行不起作用?
instance = fn.apply(instance, arguments);
较长的例子:
var createFoo = function() {
var foo = {},
fn = function() {
var i = 0;
this.increment = function() {
i++;
};
this.get = function() {
return i;
};
};
foo = fn.apply(foo, arguments) || foo;
return foo;
}, foo = createFoo();
test('foo test', function() {
foo.increment();
equal(foo.get(), 1, 'pass');
});
var createBar = function() {
var bar = {},
fn = function() {
var i = 0;
this.increment = function() {
i++;
};
this.get = function() {
return i;
};
};
bar = fn.apply(bar, arguments);
return bar;
}, bar = createBar();
test('bar tests', function() {
bar.increment(); /* undefined */
});
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply – akonsu 2014-10-09 17:49:20
什么是你贴在上面的两行之间有什么不同? – 2014-10-09 18:06:33
当你有'a || b',这将评估'a'并且在它是“truthy”时返回它,否则它将返回'b'。 – 2014-10-09 18:07:33