2015-03-19 66 views
0

原始的問題Javascript對象函數調用對象中的另一個功能,Rails的

想不通爲什麼我不能從第一函數中調用的第二功能。我正在使用jQuery-turbolinks。 (另外,如果你碰巧知道只在軌中運行頁面特定的JavaScript的更好的方法,請告訴我。目前,這是我最好的實現,在這裏我檢查身體是否有特定的類,如果它確實運行,那麼我運行這個JavaScript對象內的init函數)。

應用程序/資產/ Java腳本/ blogs.js

$(document).ready(function(){ 

    var blogsjs = { 
     myBlog: this, 
     init: function(){ 
      alert("hello from blogs"); 
      $("input").on('click', function(){ 
       $(this).hide('slow', function(){ 
        myBlog.another(); 
       }); 
      }); 
     }, 
     another: function(){ 
      alert("I was called!") 
     } 
    }; 


    if($('body').hasClass("blogs") == true){ 
     blogsjs.init(); 
    } 
}); 

解決方案之後從一個方法內反饋

只是簡單地使用object.method()語法來調用同一對象中的另一種方法:

$(document).ready(function(){ 

    var blogsjs = { 
     init: function(){ 
      alert("hello from blogs"); 
      $("input").on('click', function(){ 
       $(this).hide('slow', function(){ 
        blogsjs.another(); 
       }); 
      }); 
     }, 
     another: function(){ 
      alert("I was called!"); 
      blogsjs.yetanother(); 
     }, 
     yetanother: function(){ 
      alert("yet another called"); 
     } 
    }; 
     blogsjs.init(); 

}); 

我不喜歡這段代碼看起來有多混亂,但是我認爲,面向對象設計的封裝優勢是可靠的:每個資源的javascript只能訪問其javascript對象內的方法。

回答

1

我不知道你想與你的聲明,這部分實現的目標:

var blogsjs = { 
    myBlog: this 
} 

但是,this將不會被設置爲blogsjs。這將是上述功能中的任何內容。在Javascript中,this僅在函數調用中設置。它不是在Javascript字面聲明中設置的,因此您不能靜態聲明引用該對象本身的屬性。 JavaScript只是不支持。

如果需要,可以在構造包含對象引用的對象後添加屬性。

如果你想myBlog被初始化爲指向blogsjs,那麼你將不得不這樣做定義對象後:

var blogsjs = { 
    init: function() {...}, 
    another: function() {...} 
}; 
blogsjs.myBlog = blogsjs; 

此外,該行代碼將無法正常工作:

myBlog.another(); 

myBlog因爲是一個對象,而不是可變的屬性。它必須與其父對象一起引用。

1

因此,您可能會遇到Cannot read property 'another' of undefined異常,因爲您在blogsjs對象上指定了myBlog,但未引用該對象。另外myBlog不是是blogsjs的引用,但範圍jquery調用document.ready函數。

你需要或者創建init方法內部參考:

init: function(){ 
    var myBlog = this; 
    alert("hello from blogs"); 
    $("input").on('click', function(){ 
    $(this).hide('slow', function(){ 
     myBlog.another(); 
    }); 
    }); 
} 

或者乾脆使用blogsjs從一個範圍以上的init方法。

Have a look at this question to learn about scoping.

相關問題