यह जावास्क्रिप्ट के गुरु के लिए एक प्रश्न है। मैं जावास्क्रिप्ट प्रोटोटाइप मॉडल के साथ और अधिक सुरुचिपूर्ण काम करने की कोशिश कर रहा हूँ। यहाँ मेरी उपयोगिता कोड है (यह प्रोटोटाइप का असली श्रृंखला और instanceof ऑपरेटर के साथ सही काम प्रदान करता है): वहाँ है:मैं जावास्क्रिप्ट प्रोटोटाइप विरासत (प्रोटोटाइप की श्रृंखला) कैसे कर सकता हूं
var Class_1 = new Class({
init: function (msg) { // constructor
this.msg = msg;
},
method_1: function() {
alert(this.msg + ' in Class_1::method_1');
},
method_2: function() {
alert(this.msg + ' in Class_1::method_2');
}
});
var Class_2 = new Class({
parent: Class_1,
init: function (msg) { // constructor
this.msg = msg;
},
// method_1 will be taken from Class_1
method_2: function() { // this method will overwrite the original one
alert(this.msg + ' in Class_2::method_2');
},
method_3: function() { // just new method
alert(this.msg + ' in Class_2::method_3');
}
});
var c1 = new Class_1('msg');
c1.method_1(); // msg in Class_1::method_1
c1.method_2(); // msg in Class_1::method_2
var c2 = new Class_2('msg');
c2.method_1(); // msg in Class_1::method_1
c2.method_2(); // msg in Class_2::method_2
c2.method_3(); // msg in Class_2::method_3
alert('c1 < Class_1 - ' + (c1 instanceof Class_1 ? 'true' : 'false')); // true
alert('c1 < Class_2 - ' + (c1 instanceof Class_2 ? 'true' : 'false')); // false
alert('c2 < Class_1 - ' + (c2 instanceof Class_1 ? 'true' : 'false')); // true
alert('c2 < Class_2 - ' + (c2 instanceof Class_2 ? 'true' : 'false')); // true
मेरा प्रश्न है:
function Class(conf) {
var init = conf.init || function() {};
delete conf.init;
var parent = conf.parent || function() {};
delete conf.parent;
var F = function() {};
F.prototype = parent.prototype;
var f = new F();
for (var fn in conf) f[fn] = conf[fn];
init.prototype = f;
return init;
};
यह मुझे इस तरह के thigns करने की अनुमति देता ऐसा करने के लिए और अधिक आसान तरीका है?
http://codereview.stackexchange.com/ –
[जॉन रेसिग] (http://ejohn.org/blog/simple-javascript-inheritance/) द्वारा कक्षा विरासत का एक बहुत अच्छा उदाहरण है। यह सुपर और अन्य उपहार प्रदान करता है। – elclanrs
यह रुचि का हो सकता है: http://ejohn.org/apps/learn/ –