विज़ुअल शिक्षार्थियों के लिए, जब बिना .prototype
ExampleClass = function(){};
ExampleClass.method = function(customString){
console.log((customString !== undefined)?
customString :
"called from func def.");}
ExampleClass.method(); // >> output: `called from func def.`
var someInstance = new ExampleClass();
someInstance.method('Called from instance');
// >> error! `someInstance.method is not a function`
एक ही कोड के साथ
समारोह को परिभाषित करने, अगर .prototype
जोड़ा जाता है,
ExampleClass.prototype.method = function(customString){
console.log((customString !== undefined)?
customString :
"called from func def.");}
ExampleClass.method();
// > error! `ExampleClass.method is not a function.`
var someInstance = new ExampleClass();
someInstance.method('Called from instance');
// > output: `Called from instance`
बनाने के मैं स्पष्ट टी,
ExampleClass = function(){};
ExampleClass.directM = function(){} //M for method
ExampleClass.prototype.protoM = function(){}
var instanceOfExample = new ExampleClass();
ExampleClass.directM(); ✓ works
instanceOfExample.directM(); x Error!
ExampleClass.protoM(); x Error!
instanceOfExample.protoM(); ✓ works
**** उदाहरण के लिए नोट से ऊपर, someInstance.method(),
ExampleClass.method के रूप में निष्पादित नहीं किया जाएगा() का कारण बनता है त्रुटि & निष्पादन जारी नहीं रख सकते।
लेकिन चित्रण & आसान समझ के लिए, मैं इस क्रम रखा है। **** कोड से निकलने के लिए से ऊपर jsbin लिंक पर chrome developer console
& JS Bin
क्लिक करें उत्पन्न
परिणाम।
टॉगल ctrl + /
साथ खंड टिप्पणी की इस से लिया गया है: http://code.google.com/intl/es/speed/articles/optimizing-javascript.html यह भी है कि कहने के लिए महत्वपूर्ण है अगर हम 'MyClass' के कई उदाहरण बना रहे हैं, तो हम प्रत्येक उदाहरण के लिए एक समारोह' विशेषाधिकार प्राप्त विधि 'बना रहे हैं। हालांकि 'publicMethod' केवल सभी उदाहरणों के लिए एक बार बनाया गया है। – Menda
यहां मेंडा की टिप्पणी में उल्लिखित आलेख का एक अपडेट किया गया लिंक है: https://developers.google.com/speed/articles/optimizing-javascript –
लेकिन Function.prototype.method == Function.method क्यों है? – Raghavendra