Node js函数

时间:2018-06-25 17:28:26

标签: javascript node.js

我是Node.js的新手,无法弄清楚如何创建和使用函数。例如在我的代码中:-

var abc={
    printFirstName:function(){
        console.log("My name is abc");
        console.log(this===abc);   //Prints true
    }
};
abc.printFirstName();

//The default calling context is global
function worthless(){
    console.log("I'm worthless");
    console.log(this===global);   //Prints true
}
worthless();

我无法理解在变量abc内编写的函数与在变量abc内编写的函数之间的区别。我尝试将printFirstName函数编写为

function printFistName(){ //First Case
     console.log("My name is abc");
     console.log(this===abc);
}

但这给我一个错误。同样,我尝试将全局函数编写为

worthless:function(){ //Second Case
    console.log("I'm worthless");
    console.log(this===global);
}

,这给了我一个错误。我不明白这是怎么回事。任何帮助表示赞赏。谢谢!

修改:-

这是我在第一种情况下遇到的错误:

function printFirstName(){
             ^^^^^^^^^^^^^^

SyntaxError: Unexpected identifier
    at new Script (vm.js:74:7)
    at createScript (vm.js:246:10)
    at Object.runInThisContext (vm.js:298:10)
    at Module._compile (internal/modules/cjs/loader.js:670:28)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:713:10)
    at Module.load (internal/modules/cjs/loader.js:612:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:551:12)
    at Function.Module._load (internal/modules/cjs/loader.js:543:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:744:10)
    at startup (internal/bootstrap/node.js:240:19)

这是第二种情况下出现的错误:

worthless:function(){
                  ^

SyntaxError: Unexpected token (
    at new Script (vm.js:74:7)
    at createScript (vm.js:246:10)
    at Object.runInThisContext (vm.js:298:10)
    at Module._compile (internal/modules/cjs/loader.js:670:28)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:713:10)
    at Module.load (internal/modules/cjs/loader.js:612:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:551:12)
    at Function.Module._load (internal/modules/cjs/loader.js:543:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:744:10)
    at startup (internal/bootstrap/node.js:240:19)

1 个答案:

答案 0 :(得分:0)

在上面的代码段中,对象printFirstName中的函数abc是一种对象方法,这意味着对该函数的函数调用将使用对象的上下文,如下所示:

var obj = {
   foo: 'bar',
   func: function () {
       console.log(this.foo); // this prints 'bar'
   }
};

另一方面,函数printFirstName在外部作用域中。如果您的代码在非strict mode中运行,则该函数中对this的所有引用都对应于globalconsole是所有全局实体(如this)的根对象,并且以此类推。如果启用了严格模式,则对undefined的所有引用都将评估为printFirstName

您还想看看https://github.com/getify/You-Dont-Know-JS/blob/master/this%20%26%20object%20prototypes/ch1.md,它对此进行了详细说明。

对于尝试在对象abc外部写入printFistName的尝试,我发现有一个错字:ReferenceError: printFistName is not defined,这可能导致以下形式的错误:{{1 }}。

进入最后一个片段:

worthless: function () {
    console.log("I'm worthless");
    console.log(this === global);
}

以上语法旨在将函数声明为名为worthless的属性,并且在作为脚本的一部分运行时将导致Unexpected token SyntaxError错误。

相关问题