我想实现这个功能:
- 我有一个对象
var obj = {};
我在该 obj 上有三个属性,
obj.zero
和obj.one
&obj.binaryString
obj.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
并使one
和zero
方法可调用或不可调用,这样我就可以实现这一点功能:
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
最佳答案
只需将 obj 作为函数,然后打印你想要的内容。
function Binary () {
var obj = function(msg){ console.log(msg+this.binaryString ) };
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.zero(" is the result ")
关于javascript - 如何使属性/方法可调用或不可调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43923053/