-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththis.js
More file actions
81 lines (58 loc) · 1.17 KB
/
this.js
File metadata and controls
81 lines (58 loc) · 1.17 KB
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// this 的指向
// 1. 作为对象的方法调用
var obj = {
a: 1,
getA: function() {
alert( this === obj );
alert( this.a );
}
};
obj.getA();
// 2. 作为普通函数调用
window.name = 'globalName';
var getName = function() {
return this.name;
};
console.log( getName() );
// or
window.name = 'globalName';
var myObject = {
name: 'sven',
getName: function() {
return this.name;
}
};
var getName = myObject.getName;
console.log( getName() );
// 3. 构造器调用
var MyClass = function() {
this.name = 'sven';
};
var obj = new MyClass();
console.log( obj.name ); // output 'sven'
var MyClass = function() {
this.name = 'sven';
return {
name: 'anne'
}
};
var obj = new MyClass();
console.log( obj.name ); // output 'anne'
var MyClass = {
this.name = 'sven';
return 'anne';
};
var obj = new MyClass();
console.log( obj.name ); // output: 'sven'
// 4. Function.prototype.call or Function.prototype.apply 调用
var obj1 = {
name: 'sven',
getName: function() {
return this.name;
}
};
var obj2 = {
name: 'anne'
};
console.log( obj1.getName() ); // output: sven
console.log( obj1.getName.call( obj2 ) ); // output: anne