2017-08-04 69 views
1

我想清理我的代碼位,所以我創建一些小物件或庫(叫什麼你怎麼想),如:不能內部函數訪問功能的JavaScript

function myLib() { 
    this.get = function() { ... }; 
    ... 
}; 

問題是,當我嘗試稱它爲myLib.get()。它引發以下錯誤:

Uncaught TypeError: myLib.get is not a function 

我試圖調用封裝成$(document).ready(),但它並沒有幫助。

你能幫助我嗎?

謝謝!

+0

myLib.get()中的'myLib'是什麼? –

回答

2

MYLIB用於 「libary」,並要撥打這是「獲得」庫裏的方法。

靜態實例對你來說比較好。

const myLib = { 
    get:function(){}, 
    get2:function(){} 
    ... 
}; 
myLib.get(); 
myLib.get2(); 
1

你應該使用MYLIB作爲構造,即:

var lib = new myLib(); 
lib.get(); 
2

so I create some small objects or libraries (call it how you want)

在你的情況,你要創建一個構造函數,myLib是一個構造,而不僅僅是function,你不能訪問函數屬性和方法直接,這就是爲什麼你得到了異常。

因此,您需要獲得myLib的實例才能調用get方法或訪問其任何成員(方法)。

function myLib() { 
 
    this.get = function() { console.log("get called!!"); }; 
 
}; 
 
let lib = new myLib(); 
 
lib.get();

注:

而且從MDN Reference for Functions你可以看到:

The this keyword does not refer to the currently executing function, so you must refer to Function objects by name, even within the function body.