• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
李弈圣
博客园    首页    新随笔    联系   管理    订阅  订阅
JavaScript继承
原型链继承
window.onload=function test() {
function SuperType () {
this.property = true;
}
SuperType.prototype.getSuperValue = function () {
return this.property;
};
 
function SubType () {
this.subproperty = false;
}
 
SubType.prototype = new SuperType();
 
SubType.prototype.getSubValue = function () {
return this.subproperty;
};
 
var instance = new SubType();
alert(instance.getSuperValue());
 
组合继承
function SuperType (name) {
this.name = name;
this.colors = ["blue","green","red"];
}
 
SuperType.prototype.sayName = function () {
alert(this.name);
};
 
function SubType (name,age) {
//继承属性
SuperType.call(this,name);
this.age = age;
}
 
//继承方法
SubType.prototype = new SuperType();
SubType.prototype.constructor = SubType;
SubType.prototype.sayAge = function () {
alert(this.age);
};
 
var instance1 = new SubType("liqiang",29);
instance1.colors.push("black");
alert(instance1.colors);
instance1.sayName();
instance1.sayAge();
 
var instance2 = new SubType("mingming",30);
alert(instance2.colors);
instance2.sayAge();
instance2.sayName();
 
寄生式继承
function createAnother (original) {
var clone = Object.create(original);
clone.sayHi = function () {
alert("Hi");
};
return clone;
}
var person = {
name: "liqiang",
age: 23
};
 
var anotherPerson = createAnother(person);
anotherPerson.sayHi();
posted on 2017-10-17 21:04  李弈圣  阅读(79)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3