简体   繁体   English

在TypeScript中扩展基本类型,错误:“_这未定义...”

[英]Extend Basic Types in TypeScript, Error: “_this is not defined…”

I am trying to rewrite some of my JavaScript code in TypeScript. 我试图在TypeScript中重写我的一些JavaScript代码。 Some of this code has references to an extension I added to the string object prototype. 这些代码中的一些引用了我添加到字符串对象原型的扩展。

String.prototype.format = function () {
    var formatted = this;
    for (var i = 0; i < arguments.length; i++) {
        formatted = formatted.replace(
            RegExp("\\{" + i + "\\}", 'g'), arguments[i].toString());
    }
    return formatted;
};

However adding this with type script has been quite challenging. 但是,使用类型脚本添加它非常具有挑战性。

I have seen examples where you declare an extension of a basic interface then assign an function to the prototype to match the interface and provide your functionality. 我已经看到了一些示例,其中您声明了基本接口的扩展,然后将一个函数分配给原型以匹配接口并提供您的功能。 Like so... 像这样......

interface String {
    showString: () => string;
}

String.prototype.showString = (): string {
    return this;
};

Except this errors because "_this is not defined..." 除了这个错误,因为“_这个没有定义......”

The other things I have tried is to create a new class to extend string... 我尝试过的其他事情是创建一个新类来扩展字符串...

export class MoreString extends string {

}

However this also does not work because you can only extend classes and string/String are not classes but built in types. 但是这也行不通,因为你只能扩展类,而string / String不是类,而是内置类型。

What is the simplest way to extend String and access my extension method? 扩展String并访问扩展方法的最简单方法是什么?

I ended up running into another issue later in the day that made me see what was happening here. 当天晚些时候,我最终遇到了另一个问题,让我看到了这里发生的事情。 From the top, here it is... 从顶部开始,这里是......

TypeScript is built on top of JavaScript, so like @Nypan says JavaScript is valid TypeScript. TypeScript是建立在JavaScript之上的,所以像@Nypan所说的JavaScript是有效的TypeScript。 Because of this the differences are very easy to overlook. 因此,差异很容易被忽视。

A JavaScript function like this references the scope that the function executes in with "this". 像这样的JavaScript函数引用函数用“this”执行的范围。

var f = function (postFix) {return this + postFix};

To add TypeScript syntax you would define types 要添加TypeScript语法,您需要定义类型

var f = function (postFix: string): string {return this + postFix};

In both of these cases this refers to the scope of the function just like classic JavaScript. 在这两种情况下,这都指的是函数的范围,就像经典JavaScript一样。 However, things change when we do this... 但是,当我们这样做时,情况就会改变......

var f = (postFix: string): string {return this + postFix};
//or more correctly
var f = (postFix: string): string => {return this + postFix};

When you remove the function from in front of the parameters then it is no longer a classic function. 当您从参数前面删除该功能时,它不再是经典功能。 It becomes a "Fat Arrow" function, apparently even with out using the "=>" syntax. 它变成了“胖箭”功能,显然即使没有使用“=>”语法。 In the examples above "this" now refers to the class that the function exists in like in C#. 在上面的例子中,“this”现在指的是函数存在于C#中的类。

In my attempt to assign a function to the prototype of string I omitted the function keyword so it was interpreted as a "Fat Arrow" function and tries to bind this to the scope of the class. 在我尝试将函数分配给字符串的原型时,我省略了function关键字,因此它被解释为“Fat Arrow”函数并尝试将其绑定到类的范围。 However the function dose not exist in a class and causes the error "_this is not defined". 但是,该类函数不存在于类中并导致错误“_this not defined”。

When I add the "function" keyword, the function is interpreted as I intended and works correctly. 当我添加“function”关键字时,该函数按我的意图解释并正常工作。

interface String {
    format: () => string;
}

String.prototype.format = function () : string {
    var formatted = this;
    for (var i = 0; i < arguments.length; i++) {
        formatted = formatted.replace(
            RegExp("\\{" + i + "\\}", 'g'), arguments[i].toString());
    }
    return formatted;
};

In exactly similiar case i do it like that: 在完全相似的情况下,我这样做:

interface String {
    endsWith(str);
    startsWith(str);

}

This is just to satisfy the compiler. 这只是为了满足编译器。 You implement the methods exactly like in javascript. 您可以像在javascript中一样实现这些方法。

Hope that helps. 希望有所帮助。

I think that this is the same thing that stride was getting at but you simply extend it in javascript (javascript is valid typescript) and then interface the new functionality. 我认为这是大步相同的事情,但你只是在javascript中扩展它(javascript是有效的typescript),然后界面新的功能。

Short example: 简短的例子:

String.prototype.myExtension = function () {
   return this + " something."
};

interface String {
    myExtension : () => string;
}

alert("test".myExtension());

You need to extend the String interface like this: 您需要像这样扩展String接口:

interface String {
    stringFormat(...args: string[]): string;
}

and you need to implement like this 你需要这样实现

module Utilities {
    String.prototype.stringFormat = function (): string {
        var args = arguments;
        return this.replace(/\{\{|\}\}|\{(\d+)\}/g, function (m, n) {
            if (m == "{{") { return "{"; }
            if (m == "}}") { return "}"; }
            return args[n];
        });
    }
}

implementation source: Equivalent of String.format in jQuery 实现源: jQuery中String.format的等价物

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM