Skip to content

Instantly share code, notes, and snippets.

@nashibao
Last active December 20, 2015 02:49
Show Gist options
  • Save nashibao/6059118 to your computer and use it in GitHub Desktop.
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)
<!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>
@nashibao
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment