令人费解的绑定.如何将一个对象绑定到另一个对象

confusing bind. how to bind an object to another?

本文关键字:一个对象 绑定 令人费解      更新时间:2023-09-26

在此代码中,

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

我如何将john绑定到person,使得像

这样的东西
var Name = john.bind(person)

可以调用:

Name.full();

尝试了一些事情,得到:这一点。full不是函数OR名字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();
}

并将其绑定到person fellow:

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

:

person sdfsd

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

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

这回报:

jane austen

如果我错了请纠正我。janeName像往常一样是jane,但是this绑定到Person。但是,使用.call janeName调用是jane绑定到person并提供可选参数,这里实际上jane调用本身,提供可选参数,但反过来又绑定到person,当查找时。完整的函数。

Simple:

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

我是这样更清楚地理解bind的。而不是考虑基于类的方法调用.bind(),考虑动态作用域,考虑this,其中this将绑定到哪个函数以产生输出:

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的第一个和最后一个的输出:

john sdfsd

这个函数在Person中,叫做full;

如果我绑定完整函数约翰,引用约翰。

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

相似的,

如果我想人的输出

john.fl.call(person);

我将不得不捆绑约翰。呼叫的人。在这里,

this.full(); in john。fl 被称为由 => person.full()

将其设置为一个变量,以便在更改上下文时可以引用。

了解Bind的更多细节:

点击这里

所以一定是

这里我们将john上下文设置为Person。基于此,它返回John的Context

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