Question about "this" reserved word in JavaScript

I have a question about a reserved word thisin JavaScript.

Check the codes below:

Function.prototype.method = function (name, func) {
    if (!this.prototype[name]) {
        this.prototype[name] = func;
    }        
};

String.method('deentityify', function () {

    var entity = {
        quot: '"',
        lt: '<',
        gt: '>'
    };

    return function () {

        /*if (this === String.prototype) {
            alert('true');
        } else {
            alert('false');
        }*/

        return this.replace(/&([^&;]+);/g,
            function (a, b) {
                var r = entity[b];
                return typeof r === 'string' ? r : a;
            }
        );
    };
}());

document.write('&lt;&quot;&gt;'.deentityify());

You can edit the codes above: http://jsfiddle.net/G3Tkm/

My question is:

What is a reserved word thison line 27 return this.replace(/&([^&;]+);/g,??

I think: this === String.prototypebut this is not so.

Type '&lt;&quot;&gt;'is a string, and type thisis an object. So,this !== '&lt;&quot;&gt;'

Many thanks!

+3
source share
1 answer

Whenever I find a keyword thisin JavaScript code, I usually just look up until I find the surrounding function in it.

, . , this , .

, String.method() String. , , JavaScript .

, , , deentityify , "foo".deentityify() - , , String.method('deentityify', function () { - this, ( String.method , ).

, "foo".deentityify()() this , "foo".deentityify(). "foo".deentityify() "foo".

, this, , String, .

+5

Source: https://habr.com/ru/post/1783575/


All Articles