The document discusses prototypes in JavaScript and how they enable inheritance by allowing objects to share properties and methods from a prototype object; it provides examples of defining classes with prototypes and inheriting properties and methods from superclasses using prototypes; the document also demonstrates how to call methods from superclasses within subclasses.
2. Alipay Inc
• What is prototype?
• How to inherit?
• Simple Object
• Defining a Class
• Defining and Calling method in Class
• Calling the SuperClass from SubClass
• Overriding Method of SuperClass in SubClass
• Calling Method of SuperClass from SubClass
3. Alipay Inc
What is prototype?
By ECMASCRIPT: Each constructor is a function
that has a property named ―prototype that is
used to implement prototype-based inheritance
and shared properties.
12. Alipay Inc
How to inherit?
var CF= function (){},
CFp = {CFP1:1,CFP2:2};
CF.prototype = CFp;
CF.prototype.P1 = ‘P1’;
CF.prototype.P2 = ‘P2’;
var cf1 = new CF,
cf2 = new CF,
cf3 = new CF,
cf4 = new CF,
cf5 = new CF;
13. Alipay Inc
Simple Object
function User(){
this.firstName = ‘颂’;
this.lastName = ‘赞’;
}
var user = {firstName:’zhu’,lastName:’qi’};
User.prototype = user;
var userByConstructor = new User();
user userByConstructor
firstName zhu firstName 颂
lastName qi lastName 赞
prototypeObject? [Object] prototypeObject:user
prototype prototype
constructor:Object constructor:Function
14. Alipay Inc
function User(){
this.sex= ‘male’;
}
User.prototype = {
getSex : function (){return this.sex;}
};
function AlipayUser(){
this.sex = ‘female’;
}
function TaobaoUser(){}
AlipayUser.prototype = new User;
TaobaoUser.prototype = new User;
AlipayUser.prototype.constructor = AlipayUser;
TaobaoUser.prototype.constructor = TaobaoUser;
var alipay_user = new AlipayUser ();
var taobao_user = new TaobaoUser;
15. Alipay Inc
User
sex male
prototypeObject: Object
prototype
constructor:Function TaobaoUser
sex male
prototypeObject: Object
AlipayUser
prototype
sex female constructor:TaobaoUser
prototypeObject: Object
prototype
constructor:AlipayUser
17. Alipay Inc
Defining and Calling method in Class
function TaobaoUser(cfg){
User.call(this,cfg);
this.sex = ‘undefined’;
this.instances = this.instances || [];
this.instances.push(this);
}
TaobaoUser.getAllInstances = function (){
return this.instances;
};
TaobaoUser.prototype = new User;
TaobaoUser.prototype.setSex = function (sex){
this.sex = sex;
return this;
};
TaobaoUser.prototype.constructor = TaobaoUser;
var user = new TaobaoUser();
user.setSex(‘female’).getSex();//female;
18. Alipay Inc
Calling method of SuperClass from SubClass
User._getSelfSex_ = function (){
return this.sex || ‘This is User’s sex.’;
};
TaobaoUser.getSex = function (){
var superSex = User.prototype.getSex();
return User._getSelfSex_() + ‘ ’ + this.sex;
};
var user = new TaobaoUser;
user.getSex(); // This is User’s sex undefined;