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

时间:2015-10-24 19:31:25

标签: javascript

我试图将一个函数从一个对象绑定到一个变量而不需要外部调用bind():

var man = {
  age: "22",
  getAge: function(){
    return "My age is "+this.age;
  },
  test: function(){
    return this.getAge.bind(this);
  }
}

这有效:

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(…)

我做错了什么?

2 个答案:

答案 0 :(得分:1)

你的第二个版本中的

this并不是指你的想法,它指的是窗口,因此没有可用的属性......

注意:将()添加到结尾会调用您创建的匿名函数

答案 1 :(得分:0)

在您的示例中,this指的是写入Object文字的上下文,而不是Object literal。

您实际上无法在对象文字构建时间内引用自己,因为即使它的标识符尚未正确设置。相反,将其分为两个步骤

// 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);

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

例如,您可以将 Man 设置为继承自 Human ,并稍后使用共享代码创建 Woman

// 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