在 ES6 中,是否可以让 getter 返回一个字符串,但如果需要则返回一个属性?
一个例子:
myForm.title
// 'The foo of the bar, was there.'
myForm.title.valid
// true
我想我记得在某处看到过类似的东西,jQuery 的 $
是一个函数,但你可以调用它的方法。
最佳答案
您可以使用具有 toString
方法的对象。
var myForm = {
title: {
valid: true,
toString: function () { return 'The foo of the bar, was there.'; }
}
};
console.log(myForm.title + ''); // workaround to force to use toString
console.log(myForm.title.valid)
关于javascript - 在返回字符串的 getter 上有一个隐藏属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40333386/