javascript - Typescript 错误引用 _this

标签 javascript typescript defineproperty

我尝试在 TypeScript 中为 String.Prototype 定义一些属性:

Object.defineProperty(String.prototype, 'test', {
    value: () => {
        console.log("this is a test over text " + this);
    }
})

javaScript 原型(prototype)中,this 指调用方法的对象(在本例中为字符串值)。但是文件的编译输出是:

var _this = this;
Object.defineProperty(String.prototype, 'test', {
    value: function () {
        console.log("this is a test over text " + _this);
    }
});

TypeScript 编译器添加变量 _this 并引用它。

这是错误还是我的实现有问题?

最佳答案

Is that a bug or there is a problem in my implementation?

不,这是 TypeScript 的 arrow functions 的方式工作:在箭头函数中,this 是从创建函数的上下文中继承的,而不是由它的调用方式设置的。 (箭头函数也在 ES2015 中,至少部分受到 CoffeeScript 的“胖箭头”函数的启发;我不知道 TypeScript 的历史,也不知道它是否也是 ES2015 箭头函数的一部分灵感,反之亦然。)

这是来自上面规范链接的引述:

A function expression introduces a new dynamically bound this, whereas an arrow function expression preserves the this of its enclosing context.

Arrow function expressions are particularly useful for writing callbacks, which otherwise often have an undefined or unexpected this.

In the example

class Messenger {  
    message = "Hello World";  
    start() {  
        setTimeout(() => alert(this.message), 3000);  
    }  
};

var messenger = new Messenger();  
messenger.start();

the use of an arrow function expression causes the callback to have the same this as the surrounding 'start' method.

如果你想让 this 依赖于函数的调用方式,不要使用箭头函数,使用 function:

Object.defineProperty(String.prototype, 'test', function() {
    console.log("this is a test over text " + this);
})

另请注意 as nils points out Object.defineProperty 的第三个参数应该是属性描述符,而不是函数。您的意思可能是:

Object.defineProperty(String.prototype, 'test', {
    value: function() {
        console.log("this is a test over text " + this);
    }
});

TypeScript 转译器 doesn't change that at all ;调用"testing".test()输出"this is a test of text testing":

Object.defineProperty(String.prototype, 'test', {
    value: function() {
        snippet.log("this is a test over text " + this);
    }
});
"testing".test();
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

关于javascript - Typescript 错误引用 _this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33197501/

相关文章:

javascript - 使用 javascript 动态嵌入对象

javascript - 应用于 html5 数字字段的 javascript 的错误行为

javascript - 为什么我可以设置不可配置属性描述符的[可枚举性和]可写性?

javascript - Python打开浏览器运行javascript函数

Javascript (Modernizr/YepNope.js) 语法和用法

reactjs - React TypeScript 类型提示自动完成不适用于 Visual Studio Code 中的 React.forwardRef

node.js - 如何使用 TypeScript 编写的 Node.js 连接到 MongoDB?

javascript - 在应用程序或组件加载 Angular 7 之前运行服务

javascript - javascript中如何防止对象属性不被扩展

javascript - 'use strict' 和只读属性的奇怪行为