简体   繁体   English

确实定义时没有定义Javascript抱怨方法

[英]Javascript complaining method not defined when it is indeed defined

This might be a very easy issue. 这可能是一个非常简单的问题。 I am still learning javascript and hoping I can get help for the issue below. 我仍在学习javascript,希望我可以就以下问题获得帮助。

var hello = function()
{
    this.hey = function()
    {
        console.log("hey");
    }
    function init()
    {
        this.hey();
    }
    init();
}
var h = new hello();

The above code is complaining the method hey is not defined. 上面的代码抱怨方法未定义。 But if I do 但是如果我这样做

var h = hello();

It didn't give any issues. 它没有任何问题。

Why is the first one with the new that creates an object gave me error but the second one didn't? 为什么第一个创建对象的新对象给我错误,而第二个却没有呢? I need to create the object, thus I need to use the new keyword. 我需要创建对象,因此需要使用new关键字。 How can I resolve the error I got from first one? 如何解决第一个错误?

When you are calling hello method with new , it will create a new instance of hello function/class and you will get a this as a context of hello function . 当您使用new调用hello方法时,它将创建hello function/class的新实例,并且您将获得一个this作为hello function的上下文。

 var hello = function () {
     // this is an instance of hello class
     this.hey = function () {
         console.log("hey");
     }

     var _this = this; // creating this context of hello
     function init() {
         // this is a context of window here
         //this.hey(); // throws an error
         _this.hey(); // will execute
     }
     init();
 }
 var h = new hello(); // create a new instance/object of hello

While, when you simply calling it as a function hello() , you will get a window context inside hello function . 同时,当您简单地将其作为函数hello()调用时,您将在hello function获得window上下文。

var hello = function () {
     // this is a context of window here
     this.hey = function () {
         console.log("hey");
     }

     function init() {
         // this is a context of window here
         this.hey(); // will execute
     }
     init();
 }
 var h = hello(); // calling a hello function

JSFIDDLE DEMO: http://jsfiddle.net/8QN7W/ JSFIDDLE演示: http : //jsfiddle.net/8QN7W/

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

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