What does this mean

What is this (inside internal functions) related to the following code context? Does it point to TimeSpan?

var TimeSpan = function (days, hours, minutes, seconds, milliseconds) {
var attrs = "days hours minutes seconds milliseconds".split(/\s+/);

var gFn = function (attr) { 
    return function () { 
        return this[attr]; 
    }; 
};

var sFn = function (attr) { 
    return function (val) { 
        this[attr] = val; 
        return this; 
    }; 
};
}

thank

+3
source share
2 answers

The value is thisset implicitly depending on how the function is called , there are three cases when this happens:

  • If the link with the base object or link is not referenced:

    myFn();             // the myFn reference has no base object
    (function () {})(); // non-reference
    

    Value thiswill point to global object 1

  • If the link contains a base object, for example:

    myObj.method();
    

    The value thisinside methodwill point to myObj.

  • When a statement is used new:

    var obj = new Foo();
    

    this Foo , Foo.prototype.

this , call apply, , call:

function test(a) {
  return alert(this + a);
}

test.call("hello", " world"); // alerts "hello world"

apply, "" :

function test(a, b) {
  return alert(this + a + b);
}

var args = ["my ", "world "];
test.apply("hello ", args); // alerts "hello my world"

[1] ECMAScript 5th Strict Mode, , ( ), this undefined.

, new .

, this , .

this undefined, (this.foo = 'foo'), TypeError Foo.

+10

this , , . JavaScript , this:

var f = function() {
    this.key = "someValue";
}

console.log(f.key); // prints "someValue"

, this , TimeSpan.

+1

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


All Articles