导航
×
   ❮   
HTML CSS JavaScript PHP Go Sass W3C Colors ECMS

JS 教程

JS 简介 JS 如何使用 JS 输出 JS 语法 JS 语句 JS 注释 JS 变量 JS 运算符 JS 条件语句 JS 循环 JS 字符串 JS 数字 JS 函数 JS 对象 JS 日期 JS 数组 JS 类型化数组 JS 集合 JS Map 映射 JS Math JS 正则表达式 JS 数据类型 JS 错误 JS 事件 JS 编程 JS 关键字参考 JS 保留关键字参考 JS 运算符参考 JS 运算符优先级 JS UTF-8 字符 JS UTF-8 符号 JS UTF-8 表情符号 JS 版本

JS 高级教程

JS 对象 JS 函数 JS 类 JS 迭代 JS Promises JS 模块

JavaScript bind() 函数方法


函数借用

通过 bind() 方法,一个对象可以从另一个对象借用一个方法。

以下示例创建了两个对象(person 和 member)。

member 对象借用了 person 对象的 fullname 方法:

示例

const person = {
  firstName:"John",
  lastName: "Doe",
  fullName: function () {
    return this.firstName + " " + this.lastName;
  }
}

const member = {
  firstName:"Hege",
  lastName: "Nilsen",
}

let fullName = person.fullName.bind(member);
亲自试一试 »

保留 this

有时需要使用 bind() 方法来防止丢失 this

在下面的示例中,person 对象有一个 display 方法。在 display 方法中,this 指的是 person 对象:

示例

const person = {
  firstName:"John",
  lastName: "Doe",
  display: function () {
    let x = document.getElementById("demo");
    x.innerHTML = this.firstName + " " + this.lastName;
  }
}

person.display();
亲自试一试 »

当函数用作回调函数时,this 会丢失。

此示例尝试在 3 秒后显示人名,但会显示 undefined

示例

const person = {
  firstName:"John",
  lastName: "Doe",
  display: function () {
    let x = document.getElementById("demo");
    x.innerHTML = this.firstName + " " + this.lastName;
  }
}

setTimeout(person.display, 3000);
亲自试一试 »

bind() 方法可以解决这个问题。

在下面的示例中,使用 bind() 方法将 person.display 绑定到 person。

此示例将在 3 秒后显示人员姓名:

示例

const person = {
  firstName:"John",
  lastName: "Doe",
  display: function () {
    let x = document.getElementById("demo");
    x.innerHTML = this.firstName + " " + this.lastName;
  }
}

let display = person.display.bind(person);
setTimeout(display, 3000);
亲自试一试 »

什么是 this?

在 JavaScript 中,this关键字指的是一个对象

this关键字指的是不同的对象,具体取决于它的使用方式:

单独使用时,this 指的是全局对象
在函数中,this 指的是全局对象
在函数中,如果处于严格模式,this 的值为undefined
在对象方法中,this 指的是对象。
在事件中,this 指的是接收该事件的元素。
call()apply()bind() 这样的方法可以将 this 指向任何对象。

注意

this 不是一个变量。

this 是一个关键字。

您无法更改 this 的值。


Copyright ©2020-2026 freew3c.com All Rights Reserved 提供的内容仅用于学习和测试,不保证内容的正确性。