我这里有一些简单的代码,我正在使用Quokka和NodeJS在Visual Studio code中运行它们。
var str = "hello"
function printStr(){
console.log(this.str);
}
printStr();输出:
undefined at this.str quokka.js:6:4我可以在我的web浏览器中很好地运行这段代码,并且它工作得很好,打印出"hello“。
"use strict";未启用
发布于 2018-10-17 02:14:33
在浏览器中,this在本例中将被解释为窗口对象,并且变量str将在窗口上定义。Node中没有窗口对象。不清楚为什么要在这里使用this,而不是使用常规作用域规则。这将在浏览器和Node中工作:
var str = "hello"
function printStr(){
console.log(str); // will see outside scope
}
printStr();
更好的是,将值传递给函数,这样它就不会依赖于在其作用域之外定义的值:
var str = "hello"
function printStr(s){
console.log(s);
}
printStr(str);
Node中有一个global对象,它与浏览器的window对象有一些相似之处,所以像这样的代码可以在Node中运行,但这将是一种相当不标准的方式:
global.str = "hello"
function printStr(){
console.log(this.str)
}
printStr();发布于 2018-10-17 02:15:15
在function中,this通常指的是window对象,并且在window上没有定义变量str。
你可以简单的把它叫做
var str = "hello"
function printStr(){
console.log(str);
}
printStr();发布于 2018-10-17 02:55:06
我希望我的答案将是帮助。在节点JS中未定义对象'this‘,因为元素窗口不存在,并且您没有使用任何对象、构造函数或类。
例如:
var Animal = function(kind) {
this.name = "NN"
this.kind = kind
};
Animal.prototype.printName = function() {console.log(this.name)};
Animal.prototype.setName = function(name){this.name = name}
var a1 = new Animal("Lion");
var a2 = new Animal("Cat");
a1.setName("Robert");
a2.setName("Alex");
a1.printName();
a2.printName();请看我使用this这句话时的代码。如果你有什么问题,请写信给我!(Y)
https://stackoverflow.com/questions/52841597
复制相似问题