使用括号调用时,TypeError不是函数

时间:2015-08-05 17:16:49

标签: javascript uncaught-typeerror

我想知道为什么在hero.getSecretIdentity()中添加括号会导致TypeError,但如果我直接在我的console.log中引用它,它就可以正常工作。

var hero = {
    _name: 'John Doe',
    getSecretIdentity: function (){
        return this._name;
    }
};

var stoleSecretIdentity = hero.getSecretIdentity.bind(hero);
var stoleSecretIdentity = hero.getSecretIdentity()

//TypeError: stoleSecretIdentity is not a function
console.log(stoleSecretIdentity());

//Works without issue
console.log(hero.getSecretIdentity());

1 个答案:

答案 0 :(得分:3)

您正在调用此处的功能

var stoleSecretIdentity = hero.getSecretIdentity();  // braces call the function

所以

var stoleSecrectIdentity 

不是函数,但设置为函数返回值。

如果你这样写:

var stoleSecretIdentity = hero.getSecretIdentity; // << without braces
你可以像以后一样打电话给它

console.log(hero.getSecretIdentity());
相关问题