Last active
December 20, 2015 02:49
-
-
Save nashibao/6059118 to your computer and use it in GitHub Desktop.
How is a 'this' argument changed in javascript ? ref: [じゃあ this の抜き打ちテストやるぞー](http://qiita.com/KDKTN/items/0b468a07410d757ac609)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title></title> | |
<script type="text/javascript"> | |
'use strict'; | |
var a, b, c, e, f, fnc; | |
a = function(){ | |
console.log(this && this.constructor); | |
console.log(this); | |
var self = this; | |
var infnc = function(){ | |
console.log(self && self.constructor); | |
console.log(self); | |
console.log(this && this.constructor); | |
console.log(this); | |
} | |
infnc(); | |
}; | |
b = { | |
a: a | |
}; | |
c = { | |
b: b | |
}; | |
console.log('basic ---------------------------------'); | |
// window | |
// strict: undefined | |
a(); | |
// b | |
// infnc: undefined | |
b.a(); | |
// b | |
// infnc: undefined | |
c.b.a(); | |
console.log('change context ---------------------------------'); | |
// window | |
// strict: undefined | |
fnc = a; | |
fnc(); | |
// window | |
// strict: undefined | |
fnc = b.a; | |
fnc(); | |
// window | |
// strict: undefined | |
fnc = c.b.a; | |
fnc(); | |
// b | |
// infnc: undefined | |
fnc = c.b; | |
fnc.a(); | |
console.log('methods ---------------------------------'); | |
function d(){ | |
console.log(this && this.constructor); | |
console.log(this); | |
var self = this; | |
var infnc = function(){ | |
console.log(self && self.constructor); | |
console.log(self); | |
console.log(this && this.constructor); | |
console.log(this); | |
} | |
infnc(); | |
this.myfnc = function(){ | |
console.log(self && self.constructor); | |
console.log(self); | |
console.log(this && this.constructor); | |
console.log(this); | |
} | |
} | |
e = { | |
a: a | |
} | |
// d | |
// infnc: undefined | |
f = new d(); | |
// d | |
f.myfnc(); | |
// e.a | |
// infnc: undefined | |
new e.a(); | |
console.log('apply(call) ---------------------------------'); | |
// window | |
a.apply(window); | |
// 42 | |
a.apply(42); | |
// window | |
// strict: undefined | |
a.apply(); | |
// window | |
// strict: undefined | |
a.apply(undefined); | |
console.log('etc ---------------------------------'); | |
// window | |
// strict: undefined | |
(function(){ | |
console.log(this); | |
console.log(('a',eval)('this')); | |
})(); | |
// window | |
// strict: window | |
new Function('console.log(this && this.constructor);console.log(this);')() | |
</script> | |
</head> | |
<body> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
じゃあ this の抜き打ちテストやるぞー