【问题标题】:Javascript complaining method not defined when it is indeed defined确实定义了Javascript抱怨方法时未定义
【发布时间】:2014-09-03 09:03:25
【问题描述】:

这可能是一个非常简单的问题。我还在学习 javascript,希望能得到以下问题的帮助。

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

上面的代码抱怨没有定义方法hey。 但是如果我这样做了

var h = hello();

它没有给出任何问题。

为什么第一个创建对象的 new 给了我错误,而第二个没有?我需要创建对象,因此我需要使用 new 关键字。如何解决第一个错误?

【问题讨论】:

  • this 未在 init 中定义。
  • 如@torazaburo所说,你需要先将this分配给一个变量,这样你就可以在init的范围内调用它

标签: javascript function public


【解决方案1】:

当您使用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

虽然,当您只是将其作为函数 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 演示:http://jsfiddle.net/8QN7W/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    相关资源
    最近更新 更多