如果我将 d3.scale 函数分配给变量,我可以传入一个数字,它将正确缩放该数字。
但是,如果我将相同的函数包装在一个对象中,它不会返回我期望的答案。为什么?
var applyScale1 = d3.scale.ordinal()
.domain([0, 2])
.rangePoints([0, 1024]);
console.log(typeof(applyScale1)); // "function"
console.log(applyScale1(1)); // 0
console.log(applyScale1(5000)); // 1024 *Correct*
// But wrapping that in an object doesn't work. Why?
var obj = {
returnResult: function(n) {
var fn = d3.scale.ordinal()
.domain([0, 2])
.rangePoints([0, 1024]);
return fn(n);
},
returnFunction: function() {
return d3.scale.ordinal()
.domain([0, 2])
.rangePoints([0, 1024]);
},
withCall: function(n) {
var fn = d3.scale.ordinal()
.domain([0, 2])
.rangePoints([0, 1024]);
var nScaled = fn.call(n);
return nScaled;
},
applySelf: function(n) {
var self = this;
var fn = d3.scale.ordinal()
.domain([0, 2])
.rangePoints([0, 1024]);
var nScaled = fn.apply(self, [n]);
return nScaled;
},
usingCall: function(n) {
return d3.scale.ordinal()
.domain([0, 2])
.rangePoints([0, 1024])
.call(n);
},
};
console.log(obj.returnResult(1)); // = 0
console.log(obj.returnResult(5000)); // = 0 * Wrong *
console.log(obj.returnFunction()(1)); // = 0
console.log(obj.returnFunction()(5000)); // = 0 * Wrong *
console.log(obj.withCall(1)); // = 0
console.log(obj.withCall(5000)); // = 0 * Wrong *
console.log(obj.applySelf(1)); // = 0
console.log(obj.applySelf(5000)); // = 0 * Wrong *
console.log(obj.usingCall(1)); // = 0
console.log(obj.usingCall(5000)); // = 0 * Wrong *