Skip to content

Instantly share code, notes, and snippets.

@vvakame
Created January 31, 2013 03:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vvakame/4679934 to your computer and use it in GitHub Desktop.
Save vvakame/4679934 to your computer and use it in GitHub Desktop.
JavaScriptのthisの覚え方 ref: http://qiita.com/items/74005adacc0e8e2a3cab
var hoge = "fuga";
window.foo = "bar";
// fuga+bar と表示される
console.log(this.hoge + "+" + this.foo);
(function(){
// 同じくfuga+bar と表示される
console.log(this.hoge + "+" + this.foo);
})();
var Hoge = function Hoge(msg) {
this.hoge = msg;
this.method = function () {
console.log("method+" + this.hoge);
}
}
var obj1 = new Hoge("Hello");
var obj2 = new Hoge("World");
// Hello と表示
console.log(obj1.hoge);
// method+Hello と表示
obj1.method();
// World と表示
console.log(obj2.hoge);
// method+World と表示
obj2.method();
// しまったnewを付け忘れたのでHogeの中のthisはグローバルオブジェクトだ!
Hoge("newじゃねーよ!");
// ぎゃーっ! true!
console.log(window.hoge == "newじゃねーよ!");
// ぎゃーっ! method+newじゃねーよ!
window.method();
var hoge = {foo:"bar"};
hoge.print1 = function() {
console.log(this.foo);
};
// bar を表示
hoge.print1();
var func = function() {
console.log(this.foo);
};
// window.foo が参照されるのでundefined
func();
hoge.print2 = func;
// thisがhogeに変わったので bar と表示される
hoge.print2();
// 一応prototypeも試してみましょうね。
var Hoge = function Hoge(msg) {
this.message = msg;
};
Hoge.prototype.print = function() {
console.log("prototype+" + this.message);
}
var obj = new Hoge("Hello");
// prototype+Hello と表示
obj.print();
var hoge = {
foo: "bar",
print:function(){
console.log(this.foo);
}
};
// 何かに所属している時のthisなので bar と表示
hoge.print();
var paramour = {foo:"NTR"};
// thisをすり替えられたので NTR と表示
hoge.print.call(paramour);
var Hoge = function Hoge(msg) {
this.message = msg;
}
Hoge.prototype.print = function() {
console.log("Love " + this.message);
}
var obj1 = new Hoge("sarari-man");
// sarari-man と表示
obj1.print();
// アイエエエエ!?ニンジャ!?ニンジャナンデ!?
obj1.print.call({message:"ninja"});
// thisを保護する方法もあるよ
var ProtectedHoge = function ProtectedHoge(msg) {
this.message = msg;
// this を保存しておく
var _this = this;
this.print = (function(fn) {
// fn に元々のthis.printが入ってる。
return function() {
// 元々のthis.printを_thisに保存しておいた元々のthisを指定して実行しなおす。
fn.apply(_this, arguments);
};
})(this.print);
}
ProtectedHoge.prototype.print = function() {
console.log("Love " + this.message);
}
var obj2 = new ProtectedHoge("Fujikido");
// ドーモ、ニンジャスレイヤーです。ニンジャ殺すべし。
obj2.print.call({message:"ninja"});
class ProtectedHoge
constructor:(@message) ->
print:() =>
console.log(@message)
new ProtectedHoge("Fujikido").print()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment