简体   繁体   English

OO Javascript。 物业发行

[英]OO Javascript. Properties Issue

I come from OOP languages (Java, C# and PHP). 我来自OOP语言(Java,C#和PHP)。 I'm just doing some OOP in Javascript and am seriously confused on how to define a property. 我只是在用Java语言做一些OOP,而在如何定义属性方面却很困惑。 The code below is based on a Mozilla code example, which is the same as what I'm working with. 下面的代码基于Mozilla代码示例,与我正在使用的示例相同。 I've also included the way I thought properties should be declared, but don't seem to work. 我还包括了我认为应该声明属性的方式,但似乎不起作用。

var myExtension = {

    // This is how I thought it'd be done
this.instructionServers = new Array(
    "http://server.com/json.php",
),


init: function() {  
    // The event can be DOMContentLoaded, pageshow, pagehide, load or unload.  
    if(gBrowser) {
        gBrowser.addEventListener("DOMContentLoaded", this.onPageLoad,false);  
    }
},  

onPageLoad: function(aEvent) {  
    var doc = aEvent.originalTarget; // doc is document that triggered the event  
    var win = doc.defaultView; // win is the window for the doc  

    // Skip frames and iFrames
    if (win.frameElement) return;

    // Code removed
}  

You should have 你应该有

var myExtension = {
    instructionServers: ["http://server.com/json.php"],

    // ...

};

Alternatively, you can also assign properties in JavaScript directly, as in 另外,您也可以直接在JavaScript中分配属性,如

myExtension.instructionServers = ["http://server.com/json.php"];

This would make instructionServers an array property of myExtension . 这会使instructionServers成为myExtension的数组属性。 You can then get the value of the property with 然后,您可以使用

myExtension.instructionServers

or 要么

myExtension['instructionServers']

As an aside, note that in JavaScript you can use handy array literals. 顺便说一句,请注意,在JavaScript中,您可以使用方便的数组文字。

['hello', 3]

is equivalent to the more verbose and discouraged 相当于更加冗长和沮丧

new Array('hello', 3)
var myExtension = {
        url: 'http://server.com/json.php',
        init: function() {
            alert( this.url );
        }
}

myExtension.init();

Technically init is a property itself, just a property of type function. 从技术上讲,init本身就是属性,只是类型函数的属性。 To declare a string property simply set one the same way as above. 要声明字符串属性,只需使用与上述相同的方法进行设置即可。

To reference that property inside of your object use 要在对象内部引用该属性,请使用

this 这个

You are using the object notation (think JSON) so there is no "=". 您正在使用对象表示法(例如JSON),因此没有“ =”。 it should be : 它应该是 :

instructionServers: ["http://server.com/json.php"], structionsServers:[“ http://server.com/json.php”],

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM