2017-08-10 74 views
0

公司在那裏我的工作,現在他們正在寫某事像這一切的時候...編寫代碼的JavaScript

function art() { 
}; 
art.prototype = { sth functions, var's } 

function art() { 
}; 
art.prototype = (function() { 
return{ 
sth functions, vars 
} 
})(); 

這個又是什麼目的習慣,這是在改變什麼?

+1

你知道原型是什麼嗎? – evolutionxbox

+0

谷歌搜索原型,解釋和教程嘉豪。嗯..他們認爲這是一個好主意,將'class'添加到JavaScript。 – 2pha

回答

2

原型是JavaScript的核心功能之一。 Prototype基本上是其他對象繼承屬性的對象。每個對象都有自己的原型屬性,從中繼承其成員(屬性,方法)。

拿這個經典的多態性例如:

// Car Top Class 
 
var Car = function (brand) { 
 
    this.brand = brand; 
 
}; 
 

 
Car.prototype.say = function() { 
 
    return 'I am ' + this.brand; 
 
}; 
 

 
// Models inheriting from car 
 
function Mercedes() { 
 
    this.fourwheels = '4Matic'; 
 
}; 
 
Mercedes.prototype = new Car('Mercedes-Benz'); 
 

 
function Audi() { 
 
    this.fourwheels = 'Quatro'; 
 
}; 
 
Audi.prototype = new Car('Audi'); 
 

 
// --- 
 

 
var mercedes = new Mercedes(); 
 
var audi = new Audi(); 
 

 
console.log(`${ mercedes.say() } with ${ mercedes.fourwheels }`); 
 
console.log(`${ audi.say() } with ${ audi.fourwheels }`);

..especially通過分配的CarMercedes原型,我們正在實現產業新的實例看Mercedes.prototype = new Car('Mercedes-Benz');(奔馳將收到該車的成員)在這個例子中它對多態性起着關鍵作用。

+0

很好的解釋。也許還包括一個鏈接到stackoverflow文檔? https://stackoverflow.com/documentation/javascript/592/inheritance/723/standard-function-prototype#t=201708110825165874623 – evolutionxbox

+0

@evolutionxbox謝謝。似乎沒有新的文檔鏈接是可能的。所以不讓我保存它並在這裏指出我:https://meta.stackoverflow.com/questions/354217/sunsetting-documentation –

+1

唉。悲傷的時刻。我不知道這個決定。無論如何感謝您的考慮。 – evolutionxbox