我開始閱讀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