JavaScript 对象定义 return 一个字符串而不是整个对象

JavaScript Object definition return an String instead the entire object

我想知道我们是否可以像定义位置对象一样定义一个对象...示例:

var a = {a:'asd', b:someFunction};
console.log( a );
//Desired: 'asd'
//Actual: Object {a,b}...

console.log( a.a );
//> 'asd'
console.log( a.b );
//> function() ...

此行为适用于 location

在这一点上,我可以模拟的唯一方法是通过 toStrin

进行转义
a.toString = ()-> return a.a
console.log( ''+a )
//> 'asd'

那么,在我们的代码中是否存在一种干净的方法来实现这一点,或者这种行为只适用于系统变量?

您可以覆盖 toString() 以便无论何时在字符串的上下文中使用该对象,您都可以获得 a.a 值。但是,这不会改变 console.log(a)。如果这没有帮助,也许您应该编辑您的任务并提供有关您的用例的更多信息。

var a = {
  a: 'asd',
  b: function someFunction() {}
};
a.toString = function() {
  return this.a;
};

alert(a);
// Dialog with 'asd'

console.log('Value of a: '+a);
// Console prints 'Value of a: asd'

console.log(a);
// Exact print depends on browser, but full object details will likely be shown

我找到的解决方案是使用 String 对象:

var a = new String('asd');
a.b = someUsefullFunction

但是@jason-fetterly 说输出在很大程度上取决于您正在测试的浏览器,因此出于稳定性考虑,这在 javaScript 中不可行。

此外,如果你想要这个,我在开始时已经说过,其他要点使用 toString overide

a.toString = function(){return a.a};
console.log( ''+a )

这道题我后来学到的理论部分是(Object/Function)过载,在Java.

中是可行的