混乱的约束。如何将对象绑定到另一个对象?

时间:2015-07-21 11:01:53

标签: javascript

在此代码中,

var person = {
  first: 'person',
  last: 'sdfsd',
  full: function fullName() {return this.first +  ' ' + this.last;}
}

var john = {
    first:  'person',
    last : 'sdfsd'
}

如何将john绑定到人,例如

var Name = john.bind(person)

可以致电:

Name.full();

尝试了几件事并获得: this.full不是函数OR Name.full不是函数;

我还想了解bind是否可以在上面的对象上使用,或者对象必须是一个使用bind的函数对象?

更新

当我这样做时:

var person = {
  first: 'person',
  last: 'sdfsd',
  full: function fullName() {console.log(this.first +  ' ' + this.last);}
}

var john = {
    first:  'john',
    last : 'sdfsd',
  fl: function() {return this.full();}
}

var Name = person.full.bind(john);

Name();

我得到了

john sdfsd

所以我推断:

  • bind仅适用于函数。这是对的吗?
  • 我认为,如果我像var Name = john.fl.bind(person);那样绑定,那么 这个 就会在致电Name();时与他人联系并致电console.log(person.first + ' ' + person.last);但相反,我不得不交换2来获得正确的输出。有人能告诉我什么是绑定到什么?在x.bind(y)??

更新2 我理解的一点.bind函数:

如果我创建这样的东西:

var jane = function (first, last) {
  if (first) {this.first = first;}
  if (last) {this.last = last;}
  return this.full();
}

并将其绑定到上面的人:

var janeName = jane.bind(person);
janeName();

我明白了:

person sdfsd

在控制台中。但是,我的问题的根源是获取Jane中定义的第一个和最后一个变量,如果我可以选择:

janeName.call(jane, 'jane', 'austen');

返回:

jane austen

如果我错了,请纠正我。这是如何工作的janeName和往常一样,jane,但这个与Person绑定。 但是,使用.call janeName调用jane绑定到提供了可选args的人,这里实际上 jane 调用自身,提供了可选的args,但反过来又绑定到 .full 功能时, person

3 个答案:

答案 0 :(得分:2)

简单:

john.full = person.full;
var name = john.full();

bind方式如下:

var name = person.full.call(john);  // call the full() function using john as context

var getName = person.full.bind(john);  // create a function to get the full name from john
var name = getName();

答案 1 :(得分:0)

将此项设置为您可以在更改上下文时引用的变量。

了解更多详情bout Bind:

Click Here

所以一定是

这里我们将john上下文设置为Person。基于此,它返回约翰的语境

 var person = {
      first: 'tatdsfds',
      last: 'sdfsd',
      full: function fullName() {
         document.write("content: "+this.first +  " " + this.last);
        return this.first +  ' ' + this.last;}
    }
    
    var john = {
        first:  'John',
        last : 'Mr'
    }
    
    var Name = person.full.bind(john); //set our john context to the Person
    
    Name();

答案 2 :(得分:0)

这是我理解绑定更清楚的方式。 而不是根据基于类的方法来考虑它,而是调用 .bind() ,根据这个来考虑动态范围,以及这个将绑定到哪个函数来生成什么输出:

var person = {
  first: 'person',
  last: 'sdfsd',
  full: function fullName() {console.log(this.first +  ' ' + this.last);}
}

var john = {
    first:  'john',
    last : 'sdfsd',
  fl: function() {return this.full();}
}

如果我想要约翰的第一个和最后一个的输出:

john sdfsd

这里的功能是在Person中,名为 full ;

如果我将 完整 功能绑定到john, 请参阅john。

var Name = person.full.bind(john);

Name();

同样,

如果我想 此人的输出

john.fl.call(person);

我必须将john.fl绑定为调用 ed by person。在这里,

john.fl 中的

this.full(); =>调用person.full()

相关问题