JS中简单的this学习
1
2
3
4
5
6
7
8
9
10 |
var
x = 10; var
foo = { x: 20, bar: function () { alert( this .x); } } var
bar = foo.bar; foo.bar(); //20 bar(); //10 |
1
2
3
4
5
6 |
function
bar() { console.log( this ); } bar(); //window 其实是global对象 console.log(bar === bar.prototype.constructor); //true bar.prototype.constructor(); //bar.prototype |
1
2
3
4
5
6 |
The value of this
in a function
context is provided by the caller and determined by the current form of a call expression (how the function
call is written syntactically). If on the left hand side from the call parentheses ( ... ), there is a value of Reference type then this
value is set to the base object of this
value of Reference type. In all other cases (i.e. with
any other value type which is distinct from the Reference type), thisvalue is always set to null . But since there is no any sense in
null for
this value, it is implicitlyconverted to global object. |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 |
var
foo = { bar: function
() { console.log( this ); } }; foo.bar(); // Reference, OK => foo (foo.bar)(); // Reference, OK => foo (foo.bar = foo.bar)(); // global ( false
|| foo.bar)(); // global (foo.bar, foo.bar)(); // global |
1
2
3
4 |
function
person() { console.log( this ); } person(); //window(global) |
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。