2013-07-13 81 views
2

的代碼是在這裏:的Javascript OOP和

Father.js 

(function(){ 
function father(){ 

}; 
father.prototype.init = function(){ 
    console.log('father'); 
} 
})() 

Child.js 

(function(){ 
function child(){ 

} 

child.prototype.init = function(){ 
    console.log('child'); 
} 

var father = new father(); 
})() 

我有2個問題: 我怎麼能喊爸爸對象或子對象的腳本標記或創建任何第三方JavaScript文件之間? 第二:如何調用子類中的父對象。 我是JS的新手,並在JavaScript中使用OOP時遇到了一些問題。 非常感謝您的幫助

+3

類似'VAR父親=(函數(){...;回報父親}());' – elclanrs

+0

@elclanrs:您應該將其作爲答案發布。 – icktoofay

回答

4

你應該匿名函數的結果分配給一個變量,這樣你可以使用它沒有泄露什麼是IIFE(立即調用函數表達式)內,從而封裝一切,但構造:

var Father = (function(){ 

    // Private stuff... 

    function Father(){} 

    Father.prototype.something = function(){}; 

    return Father; // Public constructor 
}()); 

現在你可以在你的Child類使用Father,或者更好的是,使用相同的模式,但通過父類作爲參數傳遞給IIFE:

var Child = (function(_parent){ 

    function Child() { 
    _parent.apply(this, arguments); // inherit properties from Parent class 
    } 

    Child.prototype = Object.create(_parent.prototype); // inherit Parent prototype 

    Child.prototype.something = function(){}; 

    return Child; 
}(Father)); 
+0

這就是我正在尋找的。非常感謝你所有的答案。 – themyth92

+0

請注意,舊版瀏覽器(IE 8)不支持Object.create,並且Child.prototype.constructor指向錯誤的對象。如果您打算在Child intances的某個點使用'this.constructor',這可能是有價值的。 – HMR

0

答覆問題一個是你在全局範圍內定義的父親和孩子:

function father(){ 
}; 
father.prototype.init = function(){ 
    console.log('father'); 
} 
function child(){ 
} 
child.prototype.init = function(){ 
    console.log('child'); 
} 
// can't name your var father because it'll overwrite the father function 
var dad = new father(); 

您可以使用命名空間限制在全球範圍內的變量的數量:

在father.js:

var myApp=myApp || {}; 
myApp.father=... 
在child.js

var myApp=myApp || {}; 
myApp.child=... 
var dad = new myApp.father(); 

要在子對象中調用父對象,您可以執行father.call(this);使父親功能中的所有父親功能定義爲剛剛創建的子對象的this.someprop=...部分。如果你只是想訪問命名的爸爸父親實例(見上面的代碼),那麼你可以做dad.init()

更多關於繼承和原型在這裏:

Prototypical inheritance - writing up

+0

如果我這樣做,我該如何在類中包含jQuery?非常感謝您的回答 – themyth92

+0

您將jQuery添加爲第一個文件,並且您可以在任何其他包含的文件中使用$。 – HMR

0

我已經成立了一個小提琴:http://jsfiddle.net/J75Zz/

不管你有多少.js文件「散佈」你的代碼,它只是「一個代碼塊」,它被執行(好,差不多......)。

您應該使用Capitals命名對象,對象father和變量father之間已經存在衝突。

+0

請注意,Child不會重載父親的init函數http://en.wikipedia.org/wiki/Method_overloading,並且它在技術上並沒有重寫它,要麼是因爲Child沒有父親作爲原型(沒有從Father繼承init在第一位) – HMR

+0

從我的小提琴:是的,但是OP所要求的超載? Q是**第二:如何在子類**中調用父對象,並且我明白,作爲父對象子對象的簡單實例化?已經給出了答案。 –