javascript - 将 `this` 与对象文字一起使用

标签 javascript

我以为我懂 JavaScript,但看来我不懂。

我想定义一个这样的对象。 (示例来自http://www.phpied.com/3-ways-to-define-a-javascript-class/)

var apple = {
    type: "macintosh",
    color: "red",
    getInfo: function () {
        return this.color + ' ' + this.type + ' apple';
    }
}

好吧,这看起来不错,让我们打印信息......

apple.getInfo() //returns "red macintosh apple" as expected

好的,现在取出该函数并再次运行...

var func = apple.getInfo; func(); //returns "undefined undefined apple"

嗯,这不是我所期望的。显然,this被解释为window 。这不是我想要的。

我的问题是——重写 apple 的惯用的首选方法是什么?字面意思,这样 apple.getInfo返回一个可以单独运行的函数,但仍然使用对象属性?

最佳答案

this 的工作方式取决于它的调用方式。要了解 this 是什么,一个快速提示是查看调用中函数名称之前的对象。

执行apple.getInfo()使this引用apple。但是将其调用为 func() 就像调用 window.func() (假设它在全局空间中),这使得 this 引用到窗口

如果您想在函数上“强制”使用 this 的值,请执行 bind。它创建函数的副本,并强制将 this 作为传递的第一个参数。

var func = apple.getInfo.bind(apple);
// all calls to `func` will have `this` "forced" as `apple`

如果您想在调用中指定 this,但不想在 func 上永久篡改 this(例如 bind > 做到了),您可以使用 callapply:

var func = apple.getInfo;
func.call(apple);
func.apply(apple);
// Both function will have `this` as `apple` only for the call.

关于javascript - 将 `this` 与对象文字一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24468004/

相关文章:

javascript - 在 <div> 中每 5 秒显示 PHP 变量作为进度条数据

javascript - Chrome 的开发工具或 Firebug 中是否存在 "Set next statement"功能?

javascript - node.js 在 Web 开发环境中的位置在哪里?

javascript - lodash 集合 - 在集合的现有对象中添加额外的自定义属性

javascript - 在 Node js中提交表单后无法加载CSS文件

javascript - q提示2 |具有不同目标的 jQuery "on"方法

javascript - 将 DRY 应用于整个文件的多个循环

javascript - 如何在另一个 Angular 应用程序的子路由中使用 Angular 应用程序?

javascript - 如何限制 javascript/Angular 中第一个位置的空间

javascript - 使用 document.createDocumentFragment() 和 innerHTML 来操作 DOM