码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript继承

时间:2017-10-17 21:42:50      阅读:256      评论:0      收藏:0      [点我收藏+]

标签:person   object   var   one   继承   push   fun   cto   nbsp   

原型链继承
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();

JavaScript继承

标签:person   object   var   one   继承   push   fun   cto   nbsp   

原文地址:http://www.cnblogs.com/lisir-eason/p/7683914.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!