2011-07-13 73 views
2

有人可以向我解釋如何在QScriptEngine擴展中獲取命名空間?我已經設置好了,所以我有一個目錄foo/under script /,並且正在執行__init __。js文件。命名空間QScriptEngine擴展

__setupPackage__(__extension__); 
print(__extension__); 

hello = function() { return 5; }; 

在我的C++代碼: engine.evaluate( 「你好();」); //正常工作

所以我的問題是,像foo/bar/whatever(foo.bar.whatever)這樣的文件層次結構的重點是什麼,如果它們都被集成到一個全局命名空間中?我已經看到了一些例子,他們試圖在代碼中創建一個名稱空間,但我似乎無法在沒有編譯器錯誤的情況下工作。

 foo = { 
      hello : function() { return 5; } 
     }; 

,在我的C++代碼:

 engine.evaluate("foo.hello();"); 

我誤解的Qt處理命名空間的方式嗎?是否應該將所有事情都撮合到全球範圍內,而不管它是從哪個文件中提取的?有沒有一個適當的例子來創建這些類型的命名空間?謝謝。

+0

是有可能,QScript不允許你創建對象文本?試試'foo = new Object; foo.hello = function(){};'而不是。 –

回答

0

JavaScript中不存在名稱空間(如C++語言中已知的)。得到的JS命名樣行爲的唯一方法是在一個對象,在該對象的名稱定義命名空間

這個例子將創建JS一個「命名空間」富,包含一方法「酒吧」封裝的東西,和一個包含方法'hello'的命名空間'foo.baz':

var foo = { 
    bar : function(){ return 5; }, 
    baz : { 
     hello : function(who){ return 'Hello ' + who + '!'; } 
    } 
}; 

希望這可以幫助你一點。

+0

恩,它實際上沒有。我知道JavaScript沒有「真正的」命名空間,但正如你可以在我的例子中看到的,我已經嘗試把一個函數放在一個對象中,但是我得到一個解析錯誤,這是我的實際問題。謝謝。 – voodoogiant

+0

@voodoo我知道你嘗試過,但在你的文章中,你忘記了'foo'前的'var'關鍵字。這是否有可能導致錯誤? –

+0

是的,我嘗試過,沒有變種。 – voodoogiant

0

在JavaScript中,我們通過使用閉包來模擬名稱空間。這也是有用的隱藏您的命名空間中的某些功能和特性,你不希望開拓,以用戶

(function(window, undefined){ 
    //declare a local object 
    myNamespace = {}; 

    //define private variables 
    var privateVar; // this wont be accessable outside of the closure 

    var privatefunct = function() { 
    alert('I can only be called by functions defined within the closure'); 
    } 

    myNamespace.publicVar = "this can be accessed outside the namespace"; 

    // this function can be called outside the closure 
    myNamespace.getPrivateVar = function() { 
    return privateVar; 
    } 

    //add your local object to the global object (aka. window in the browser) 
    window.myNamespace = myNamespace; 
})(window) 

這種模式被部分地從jQuery的借用,但它有幾個優勢,因爲它可以保護mallicious代碼的代碼可能會嘗試更改窗口的值或未定義。

林不知道這是否完全回答你的問題,但我希望它有幫助!

0

如果複製代碼QScriptEngine是一個JavaScript實現,那麼

var foo = { 
      hello : function() { return 5; } 
     }; 

var foo = {}; 
foo.hello = function() { return 5; }; 

必須工作就好了。否則,請提供您正在獲取的語法錯誤的確切文本。

如果你確實需要的命名空間,你可以考慮我TIScript:http://www.codeproject.com/KB/recipes/TIScript.aspx

+0

我得到的確切錯誤是第一行的「Parse Error」。如果我能得到上面的例子,我怎麼可能考慮讓TIScript在QScriptEngine中工作? – voodoogiant

相關問題