Ext.Function中定義了如下一個叫做flexSetter的函數,其作用看看就明白
問題在於 其中做a===null判斷的地方為什麼不用a==null呢?
源碼如下:
Ext.Function = {
/**
* A very commonly used method throughout the framework. It acts as a wrapper around another method
* which originally accepts 2 arguments for `name` and `value`.
* The wrapped function then allows "flexible" value setting of either:
*
* - `name` and `value` as 2 arguments
* - one single object argument with multiple key - value pairs
*
* For example:
*
* var setValue = Ext.Function.flexSetter(function(name, value) {
* this[name] = value;
* });
*
* // Afterwards
* // Setting a single name - value
* setValue('name1', 'value1');
*
* // Settings multiple name - value pairs
* setValue({
* name1: 'value1',
* name2: 'value2',
* name3: 'value3'
* });
*
* @param {Function} setter
* @returns {Function} flexSetter
*/
flexSetter: function(fn) {
return function(a, b) {
var k, i;
if (a === null) {
return this;
}
if (typeof a !== 'string') {
for (k in a) {
if (a.hasOwnProperty(k)) {
fn.call(this, k, a[k]);
}
}
if (Ext.enumerables) {
for (i = Ext.enumerables.length; i--;) {
k = Ext.enumerables[i];
if (a.hasOwnProperty(k)) {
fn.call(this, k, a[k]);
}
}
}
} else {
fn.call(this, a, b);
}
return this;
};
},
哈哈 結貼
作者的思路是過濾null不過濾undefined 也就是說 作者允許這樣
var myObj={
setValue:Ext.Function.flextSetter(function(name,value){
this[name]=value;
})
};
myObj.setValue(null,"none");
而不允許這樣
var myObj={
setValue:Ext.Function.flextSetter(function(name,value){
this[name]=value;
})
};
myObj.setValue();
第一種容錯 第二種不容錯,容錯處理點到為止,不過頭