在JavaScript中, “this”是一个关键字,它在不同的环境下,代表的含义不同,关于“this”的详细解释,可以参考“深入浅出 JavaScript 中的 this”。下面将介绍在WeX5中,在不同的场景下“this”的使用。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
var Model = function (){ this .callParent(); this .name = "hello" ; }; Model.prototype.getFullName = function (){ return this .name + " world" ; }; Model.prototype.say = function (){ console.log( this .name); console.log( this .getFullName()); $.ajax({ type: "GET" , url: require.toUrl( './json/postData.json' ), dataType: 'json' , async: false , cache: false , success: function (data){ console.log( this .name); console.log( this .getFullName()); }, error: function (){ alert( "加载数据失败" ); } }); }; |
代码分析:
- 第9行和第10行代码:代码正确;因为这两行代码的执行环境是Model.prototype.say,this表示当前Model的实例,可以通过this直接访问当前Model实例上的name属性和getFullName方法;
- 第18行和第19行代码:代码错误;因为这两行代码的执行环境是success回调方法,this是回调函数自身,不能通过this访问Model实例上的name属性和getFullName方法。
如果期望在success回调函数中调用Model实例上的name属性和getFullName方法,应该怎么做呢?
答案是:可以先声明一个变量指向Model实例,之后在success回调函数中使用这个变量调用Model实例的属性和方法,例如
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
var Model = function (){ this .callParent(); this .name = "hello" ; }; Model.prototype.getFullName = function (){ return this .name + " world" ; }; Model.prototype.say = function (){ console.log( this .name); console.log( this .getFullName()); var self = this ; $.ajax({ type: "GET" , url: require.toUrl( './json/postData.json' ), dataType: 'json' , async: false , cache: false , success: function (data){ console.log(self.name); console.log(self.getFullName()); }, error: function (){ alert( "加载数据失败" ); } }); }; |