Javascript 如何将绑定对象函数指定给另一个对象属性?

Javascript 如何将绑定对象函数指定给另一个对象属性?,javascript,Javascript,我尝试将一个函数从一个对象绑定到某个变量,而无需外部调用bind(): 这项工作: var a = man.test(); a(); // "My age is 22" 但当我尝试更改代码中的某些内容时: var man = { age: "22", getAge: function(){ return "My age is "+this.age; }, test: function(){ return this.getAge.bind(this); }()

我尝试将一个函数从一个对象绑定到某个变量,而无需外部调用bind():

这项工作:

var a = man.test();
a();
// "My age is 22"
但当我尝试更改代码中的某些内容时:

var man = {
  age: "22",
  getAge: function(){
    return "My age is "+this.age;
  },
  test: function(){
    return this.getAge.bind(this);
  }()//there it's, that do not do "var a = man.test()", but "var a = man.test"
}
JavaScript给了我一个错误:

Uncaught TypeError: Cannot read property 'bind' of undefined(…)

我做错了什么?

在您的第二个版本中,此
不是指您认为它是什么,而是指窗口,因此没有可用的属性


注意:将
()
添加到末尾将调用您在示例
中创建的匿名函数,此
指的是写入对象文字的上下文,而不是对象文字

您不能在对象文本的构造时实际引用您自己,因为即使是它的标识符也尚未正确设置。相反,将其分为两个步骤

// 1, set up with a literal
var man = {
    age: "22",
    getAge: function () {
          return "My age is " + this.age;
    }
}
// 2, set up things needing references to the object we just made
man.test = man.getAge.bind(man);

根据您的具体示例,您可能会多次重复此模式,您确定使用构造函数不是更好吗?这也意味着您可以使用继承和原型

例如,您可以将男人设置为继承自人类,并在以后使用共享代码创建女人

// Common category
function Human(age) {
    this.age = age;
    this.test = this.getAge.bind(this);
}
Human.prototype = Object.create(null);
Human.prototype.getAge = function () {
    return 'My age is ' + this.age;
};

// specific category
function Man(age) {
    Human.call(this, age);
}
Man.prototype = Object.create(Human.prototype);
Man.prototype.gender = function () {
    return 'I am male.';
};

// then
var man = new Man('22'); // as you used a string age
var a = man.test;
a(); // "My age is 22"
后来

// another specific category
function Woman(age) {
    Human.call(this, age);
}
Woman.prototype = Object.create(Human.prototype);
Woman.prototype.gender = function () {
    return 'I am female.';
};

// then usage
var woman = new Woman('22'); // as you used a string age
woman.getAge(); // "22", because getAge was common to humans

很难说你到底想做什么。如果希望普通属性访问像函数调用一样,那么可以使用。不,我只想编写“var a=man.test”,而不调用“var a=man.test()”,然后,
。test
要么是一个静态属性,要么像我在前面的评论中提到的那样使用getter。这是你的两个选择。它不一定是
窗口
,但是的,它指的是写入对象文本的上下文,而不是对象literal@PaulS.+1我假设它指的是窗口:-/
// another specific category
function Woman(age) {
    Human.call(this, age);
}
Woman.prototype = Object.create(Human.prototype);
Woman.prototype.gender = function () {
    return 'I am female.';
};

// then usage
var woman = new Woman('22'); // as you used a string age
woman.getAge(); // "22", because getAge was common to humans