2010-10-21 81 views
3

HI,使用原型對象正確

我有一個與對象文本語法編寫的JavaScript程序:

var MyJsProgram = { 

    someVar: value1, 
    somevar2: value2, 

    init : function() { 
     //do some initialisation 
    }, 

    libraryFunction : function() { 

    }, 

    getStyle : function() { 

    }, 

    extend : function() { 

    } 
} 

只能有一次運行該腳本的多個實例。我應該將普通方法移入myJsProgram的原型對象嗎?如果是這樣,是這個語法正確嗎?

var MyJsProgram = { 

    someVar: value1, 
    somevar2: value2, 

    init : function() { 
     //do some initialisation 
    }, 

    //more methods/members here that are unique to each instance 
} 

myJsProgram.prototype = { 
    //all shared methods here 
} 

+0

這是關於繼承? ''程序'類'擴展了幾個類像'子程序'? – Harmen 2010-10-21 13:23:27

回答

2

不,語法是不正確的(無犯罪);)

你需要創建一個對象,使用它的原型。這意味着你需要一個構造函數(這是JavaScript中的一個函數)。適用於您的問題:

var MyJsProgram = function (value1, value2) { 
    // "this" refers to the current instance of this object 
    this.someVar = value1; 
    this.someVar2 = value2; 
    // do some initialization 
}; 

創建新的對象是這樣的:

var jsProgramInstance = new MyJsProgram(value1, value2); 

原型是這些對象的實例成員。他們是這樣定義的:

MyJsProgram.prototype.someSharedMethodName = function() { 
    // do shared method stuff here 
    // (this.someVar and this.someVar2 are available here) 
}; 

使用它們像這樣(在先前創建的實例):

jsProgramInstance.someSharedMethodName(); 

你應該做到以下幾點,因爲它覆蓋現有的原型特性,這種特性存在(由於繼承):

MyJsProgram.prototype = { 
    someSharedMethodName: function() { 
     // ... 
    }, 
    // ... 
}; 
+0

no offsense taken :) – 2010-10-21 14:15:07

3

首先,創建一個函數,從中可以創建實例

// Make it a function, so you can make a new instance 
var stdProgram = function(){}; 

// All shared methods go here 
stdProgram.prototype = { 
    echo: function(message){ 
    alert(message); 
    }, 
    extend: function(key, value){ 
    this[key] = value; 
    } 
}; 

然後,你可以讓你的具體「程序」,實際上只是在基類的實例

// And here you can make instances for specific programs 
var myFirstProgram = new stdProgram(), 
    mySecondProgram = new stdProgram(); 

myFirstProgram.extend('unique', function(){ 
    alert('I am unique'); 
}); 

mySecondProgram.aVar = 'test'; 

爲了確保一切正常,試試這個:

myFirstProgram.unique();  // Should alert I am unique 
mySecondProgram.unique(); // Should throw an error, unique is undefined 

alert(mySecondProgram.aVar); // Should alert test 
alert(myFirstProgram.aVar); // Should echo undefined 

myFirstProgram.echo('hi'); // Should alert hi 
mySecondProgram.echo('hi'); // Should alert hi 
+0

這個答案有更多的投票,但是後面的帖子表示不要在創建原型時使用該語法,因爲它會覆蓋任何現有的原型屬性。我知道這是正確的,但如果我知道唯一的原型屬性將在stdProgram.prototype = {}那麼它應該沒關係......對吧? – 2010-10-21 13:56:03

+0

@elduderino:你可以覆蓋'prototype'屬性,但不建議這樣做,因爲它破壞了繼承(這就是原型的全部內容)。 – jwueller 2010-10-21 13:59:00

+0

@elusive ...但爲什麼會打破繼承?如果我知道所有繼承的屬性都將在該原型對象中,那麼繼承會被破壞到什麼地步? – 2010-10-21 14:17:42