我想实现这个功能:
- 我有一个对象
var obj = {}; 我在那个 obj 上有三个属性,
obj.zero&obj.one&obj.binaryStringobj.zero&obj.one是方法,obj.binaryString而是字符串
当我链接属性时,我希望它们将各自的数字添加到binaryString. 例如:
obj.one.zero.zero.one=> 使obj.binaryString=1001
obj.one.zero.one.one.zero=> 使obj.binaryString=10110
我已经实现了上述功能:
function Binary () {
var obj = { binaryString: '' };
Object.defineProperty(obj, 'zero', {
get: function() {
obj.binaryString += '0';
return obj;
}
});
Object.defineProperty(obj, 'one', {
get: function() {
obj.binaryString += '1';
return obj;
}
});
return obj;
}
var binary = new Binary();
binary.one.zero.zero.one // => obj.binaryString becomes '1001'
现在我想注销已完成的binaryString,加上additionalString我用下面的代码完成的:
// placed inside Binary constructor function
Object.defineProperty(obj, 'log', {
get: function() {
return function(additionalString) {
console.log(obj.binaryString + additionalString);
};
}
});
所以用这个当前的代码我可以做到这一点:
binary.one.zero.one.zero.one.log(' is the answer');
// logs out `10101 is the answer`
我想要做的是摆脱log和使oneandzero方法可调用或不可调用,以便我可以实现此功能:
binary.one.one.zero.one(' is the result')
// => logs out `1101 is the result`
我怎样才能做到这一点?
我相信它的功能类似于Chalk的工作原理:
chalk.blue.bold('Hello world!');
// `blue` is not invoked here but it adds the color blue to the style
chalk.blue('Hello world!');
// `blue` IS invoked here. It adds blue to the style and returns the stylized string