简体   繁体   English

console.log不会打印未定义吗?

[英]console.log does not print undefined?

I am new to Javascript. 我是Java语言的新手。 I am trying to understand where "this" is bound to using different examples. 我试图通过使用不同的示例来了解“ this”在哪里。 I am using console.log to print some values as shown below. 我正在使用console.log打印一些值,如下所示。

function FuncObject(value) { 
    this.answer = value;
    this.get_answer = function () { 
       return this.answer;
    }
};

var f = new FuncObject(42);

var fanswer = f.get_answer;
console.log(fanswer())

console.log prints "function" instead of "undefined". console.log打印“功能”而不是“未定义”。 document.writeln seems to print "undefined" which is the right one because this is bound to the window object which does not have answer. document.writeln似乎打印“ undefined”,这是正确的,因为它绑定到没有答案的窗口对象。 Now printing function confuses me. 现在打印功能使我感到困惑。 Now I am wondering what i should be using for logging. 现在我想知道我应该使用什么日志记录。 I am unable to find an explanation for this. 我找不到对此的解释。

thanks mohan 谢谢莫汉

Just incase you didn't notice, there's a typo in your posted code of 万一您没注意到,您发布的代码中有一个错字
this.get_answer = funcition () this.get_answer = funcition()

With that in mind, I'm not entirely sure of your experience level so let me cover all the bases. 考虑到这一点,我不确定您的经验水平,因此让我涵盖所有基础。

function FuncObject(value) { 
   this.answer = value; 
   this.get_answer = function () { 
     return this.answer; 
   } 
};

var f = new FuncObject(42);

var fanswer = f.get_answer;
console.log(fanswer())

You're setting fanswer = f.get_answer where f.get_answer is a function, so as such it sets fanswer to the function equivalent of this.get_answer . 你设置fanswer = f.get_answer其中f.get_answer是一个函数,所以因此它设置fanswer功能相当于this.get_answer

If you want the return value of f.get_answer you need to call f.get_answer() , which returns 42. 如果要返回f.get_answer的返回值, f.get_answer需要调用f.get_answer() ,它返回42。

With what you put, console.log(fanswer()) does print undefined as expected. 使用您输入的内容, console.log(fanswer()) 确实按预期打印出未定义的内容
If you simply do console.log(fanswer) it records it as function , also as expected. 如果您只是简单地进行console.log(fanswer)它将记录为function ,也符合预期。

I'm not sure why you would receive function as you stated in your question, because I definitely do not, jsbin . 我不确定为什么您会收到问题中提到的功能 ,因为jsbin绝对不会。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM