javascript: 将方法和字符串分配给相同的 属性 名称

javascript: Assign method and string to the same property name

我知道我会得到那些说我根本不应该这样做的人,但我很好奇人们是如何做到的。

我知道我已经看到您可以在哪里键入 属性 的名称并获得一个值,但随后您将括号添加到末尾并访问一个方法。

在视觉上,我是这样说的:

foo returns 'bar'
foo() performs a function

问题是如何?

由于对象属性的解析方式,这是不可能的。这是唯一接近的东西:

function f() {
  return 'I am being returned from the function.';
}

f.toString = function () {
  return 'I am a property on the variable.';
}

console.log('f() says: ' + f());
console.log('f says: ' + f);

依赖于JS在某些场景下通过.toString方法进行类型转换的功能

不,但有点……

这可以种类valueOf

一起完成

var foo = function() {
  console.log("From Function");
  return "Function";
};

foo.valueOf = function() {
  return "Variable";
};

alert( 'Output is: ' + foo() )
alert( 'Output is: ' + foo   )

这不能用 JavaScript 完成,因为对象中的项目可以是两个不同的对象。

If you want a property to be a function and an object, that's different

注意,解决方法是利用 setTimeout

var foo = (function() {
  var fn = function() {
    return foo && typeof foo === "string" ? function() {
      return "foobar"
    } : "bar";
  };
  setTimeout(function() {
    foo = fn()
  });
  return fn()
}());

console.log(foo); // `"bar"`

setTimeout(function() {
  console.log(foo()); // `"foobar"`
});