Search

4/08/2009

javascript inheritance - Object Masquerading

JavaScript Inheritance - 拒绝空谈,拒绝复杂 - JavaEye技术网站
JavaScript is an object-oriented, weak typing checked and interpreted language.

A truly object-oriented language must support inheritance, the capability of a class to reuse (inherit) methods and properties from another class.

Object Masquerading

Object masquerading supports multiple inheritance, meaning that a class can inherit from multiple superclasses.

A constructor assigns all properties and methods (with the Constructor Paradigm of class declaration) using the this keyword. Because a constructor is just a function, you can make the constructor of ClassA into a method of ClassB and call it. ClassB receives the properties and methods defined in ClassA’s constructor.


function ClassA(color){
this.color = color;
this.sayColor = function(){
alert(this.color);
};
}

function ClassB(color, name){
this.newMethod = ClassA;
this.newMethod(color);
delete this.newMethod;
this.name = name;
this.sayName = function(){
alert(this.name);
};
}
var s = new ClassB("red","nice");
s.sayColor();
s.sayName();

ClassC can masquerade as ClassA by adding ClassA’s constructor. ClassC can also masquerade as ClassB by adding ClassB’s constructor. In a word, you can implement multiple inheritance by Object Masquerading.

JavaScript provides 2 methods for object masquerading: call () and apply (). Object masquerading is not intended.

Prototype Chaining

The form of inheritance actually intended for use in JavaScript is prototype chaining. Any object has a property named prototype. You can declare ClassA’s prototype is ClassB. Then ClassB’s all properties and methods are added into ClassA’s all instances. The prototype chaning has no supports for multiple inheritance.

Make sure your constructor has no parameters.

function ClassA(){
}
ClassA.prototype.color = "";

ClassA.prototype.sayColor = function(){
alert(this.color);
}
function ClassB(){}
ClassB.prototype = new ClassA();
ClassB.prototype.name = "";
ClassB.prototype.sayName = function(){
alert(this.name);
}
var a = new ClassA();
var b = new ClassB();
a.color = "red";
b.color = "black";
b.name = "nice";
a.sayColor();
b.sayColor();
b.sayName();

Hybrid Method
Object masquerading is not intended, and prototype chaining loses the ability of constructor with parameters. To solve this problem, you can use both technologies.

function ClassA(color){
this.color = color;
}
ClassA.prototype.sayColor = function(){
alert(this.color);
}
function ClassB(color, name){
ClassA.call(this, color);
this.name = name;
}
ClassB.prototype = new ClassA();
ClassB.prototype.sayName = function(){
alert(this.name);
}
var a = new ClassA("red");
var b = new ClassB("black","nice");
a.sayColor();
b.sayColor();
b.sayName();

沒有留言: