簡體   English   中英

確實定義時沒有定義Javascript抱怨方法

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

這可能是一個非常簡單的問題。 我仍在學習javascript,希望我可以就以下問題獲得幫助。

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

上面的代碼抱怨方法未定義。 但是如果我這樣做

var h = hello();

它沒有任何問題。

為什么第一個創建對象的新對象給我錯誤,而第二個卻沒有呢? 我需要創建對象,因此需要使用new關鍵字。 如何解決第一個錯誤?

當您使用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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM