これを node.js に入力すると、undefined.
var testContext = 15;
function testFunction() {
console.log(this.testContext);
}
testFunction();
=>undefined
キーワードなしvarで合格 (=>15)。Chrome コンソールで動作しています (varキーワードの有無にかかわらず)。
これを node.js に入力すると、undefined.
var testContext = 15;
function testFunction() {
console.log(this.testContext);
}
testFunction();
=>undefined
キーワードなしvarで合格 (=>15)。Chrome コンソールで動作しています (varキーワードの有無にかかわらず)。
ドキュメントに記載されているように
Node.js モジュール内の var something は、そのモジュールに対してローカルになります。
したがって、 がvar testContextモジュール コンテキストにあり、 this のコンテキストが であるため、異なるものになりますglobal。
または、次を使用できます。
global.testContext = 15;
function testFunction() {
console.log(this.testContext);
}
testFunction();
問題はthisキーワードに関係していると思います。実行console.log(this)すると、testContext が定義されていないことがわかります。あなたは試してみたいかもしれません:
this.testContext = 15;
function testFunction() {
console.log(this.testContext);
}
testFunction();