सरल जेएस विरासत को देखते हुए, इन दो उदाहरणों के बीच आधार कार्य में व्यावहारिक अंतर क्या है? दूसरे शब्दों में, जब किसी व्यक्ति को प्रोटोटाइप (या दूसरी तरफ) के बजाय "इस" पर फ़ंक्शन को परिभाषित करना चुनना चाहिए?इस.फंक्शन और प्रोटोटाइप.फंक्शन के बीच क्या अंतर है?
मेरे लिए दूसरा उदाहरण पचाने में आसान है, लेकिन इसके लिए और भी कितना है?
समारोह इस पर परिभाषित:
//base
var _base = function() {
this.baseFunction = function() {
console.log("Hello from base function");
}
};
//inherit from base
function _ctor() {
this.property1 = "my property value";
};
_ctor.prototype = new _base();
_ctor.prototype.constructor = _ctor;
//get an instance
var instance = new _ctor();
console.log(instance.baseFunction);
समारोह प्रोटोटाइप पर परिभाषित: प्रोटोटाइप पर
//base
var _base = function() {};
_base.prototype.baseFunction = function() {
console.log("Hello from base function");
}
//inherit from base
function _ctor() {
this.property1 = "my property value";
};
_ctor.prototype = new _base();
_ctor.prototype.constructor = _ctor;
//get an instance
var instance = new _ctor();
console.log(instance.baseFunction);
संभव डुप्लिकेट कन्स्ट्रक्टर?] (http://stackoverflow.com/questions/4508313/advantages-of-using-prototype-vs-defining-methods-straight-in-the-constructor) –