関数bob
はグローバルスコープから呼び出されます。したがって、作成した変数を上書きしているthis.test
という名前のグローバル変数を指しています。test
実行するconsole.log(window.test)
と、何が起こっているのかがわかります。
コードが意図したとおりに動作するには、次のいずれかが必要になります
function Test(n) {
this.test = n;
// If a function needs 'this' it should be attached to 'this'
this.bob = function (n) {
this.test = n;
};
this.fn = function (n) {
// and called with this.functionName
this.bob(n);
console.log(this.test);
};
}
また
function Test(n) {
this.test = n;
var bob = function (n) {
this.test = n;
};
this.fn = function (n) {
// Make sure you call bob with the right 'this'
bob.call(this, n);
console.log(this.test);
};
}
またはクロージャーベースのオブジェクト
// Just use closures instead of relying on this
function Test(n) {
var test = n;
var bob = function (n) {
test = n;
};
this.fn = function (n) {
bob(n);
console.log(test);
};
}