【问题标题】:Javascript this and naming vs. not naming variablesJavascript this 和命名与不命名变量
【发布时间】:2017-07-23 11:15:06
【问题描述】:
"use script";

var user = {
    name: "John Doe",
    career: "Civil Engineer",
    socialMedia: {
        fb: "www.facebook.com/johndoe",
        twitter: "www.twitter.com/johndoe"
    },
    about: function() {
        console.log("My name is " + this.name + " and I am a " + this.career);
    }
}

var name = "Jen";
var career = "Dentist";

user.about();

var newAction = user.about;

newAction(); // My name is undefined and I am a undefined

为什么newAction() 返回未定义的姓名和职业,但是当我从以下位置删除var 时:

var name = "Jen";
var career = "Dentist";

name = "仁"; 职业 = "牙医";

然后我再次执行newAction() 并得到:

newAction() // My name is Jen and I am a Dentist

【问题讨论】:

  • 应该使用脚本做什么??
  • 如何定义、声明等一个没有名称的变量?没有标识符?如果你排除var,那么它将是一个全局的,它的所有错误都会给你带来不必要的悲伤。

标签: javascript node.js function this


【解决方案1】:

nodejs 代码不在全局范围内运行,而是在某种函数实例中运行:

//(function(module){
  var some=5;
 console.log(global.some);//undefined
//})(..)

所以如果你声明一个变量,它不是 this 所指的 global 的一部分,它只是在不可见的函数范围内(这与 var 浏览器的区别在最高范围内是窗口的一部分)。

如果你放弃声明(不好,不是在严格模式下),它会在全局范围内,因此成为 global 又名 this 函数的一部分。可以这样做:

global.name="John";
newAction();//this===global

The 'this' keyword behaves differently in Nodejs and browser

【讨论】:

    猜你喜欢
    • 2013-03-25
    • 2014-07-05
    • 2017-01-04
    • 1970-01-01
    • 2012-08-26
    • 2016-04-08
    • 1970-01-01
    • 2014-03-09
    • 2021-06-22
    相关资源
    最近更新 更多