JavaScript context

var User = {
    Name: "Some Name", Age: 26,
    Show: function() { alert("Age= "+this.Age)}; 
};

function Test(fn) {
    fn();         
}

Test(User.Show);

================

The warning displayed by the code is "Age = Undefined". I understand that the User.Show function is called internally by Test (), references 'this' to the Test () function, and not to the User object. My question is, is there a way to solve this problem?

+3
source share
6 answers

The way to solve this problem is to pass the object you are viewing "this" inside the test function ...

function Test(fn, scope, args) {
    fn.apply(scope, args);
}

Test(User.Show, User, []);

If the args array allows you to optionally pass any arguments that may arise. You can also leave the test function as is and simply pass an anonymous function ...

Test(function() {User.Show()});
+7
source

User - Test .

function Test(fn, scope) {
    fn.apply(scope || window);
}

, .

Test(User.Show, User) Age= 26.

+5

:

Test(User.Show.bind(User));

, , :

function Test(fn, scope) {
    fn.apply(scope || window);
}

Test(User.Show, User)

.

, :

JavaScript

, , .
, , :)

+2

2 . 1- }, function() { alert("Age= "+User.Age);}, , , .

+1

: call()

var User = {
    Name: "Some Name", 
    Age: 26,
    Show: function() { alert("Age= "+this.Age);} 
};

function Test(fn,obj) {
    fn.call(obj);         
}

Test(User.Show, User);

- John Resig JavaScript,

+1
var User = {
    Name: "Some Name", 
    Age: 26,
    Show: function() { alert("Age= "+User.Age)}
};

function Test(fn) {
    fn();
}
Test(User.Show);

! 'this' 'Test()', 'User'

- 'this'

0

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


All Articles