在返回字符串的getter上有一个隐藏属性

Have a hidden property on a getter that returns a string

本文关键字:有一个 隐藏 属性 getter 返回 字符串      更新时间:2023-09-26

在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)

相关文章: