js对象的创建和继承

来源:互联网 发布:linux查看普通用户 编辑:程序博客网 时间:2024/05/24 01:18

js对象的创建和继承


1、对象的创建

创建对象的设计模式有很多种,这里采用动态原型模式,是最优的方案。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"><title>Document</title></head><body><script type="text/javascript">function Person (name,age,job) {// 属性this.name = name;this.age = age;this.job = job;this.arr = ["hehe","hh"];//方法if(typeof this.sayName != "function"){Person.prototype.sayName = function(){alert(this.name);};}}var friend = new Person("Nicholas",29,"Soft Engineer");friend.arr.push("ee");alert(friend.arr);var friend1 = new Person("mike",20,"ss");alert(friend1.arr);</script></body></html>

2、对象的继承

关于对象继承的设计模式有很多种,这里采用寄生组合式继承,是最优的方案。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"><title>Document</title></head><body><script type="text/javascript">function object(o){function F(){}F.prototype = o;return new F();}function inheritPrototype (subType,superType) {var prototype = object(superType.prototype);prototype.constructor = subType;subType.prototype = prototype;}function SuperType(name){this.name = name;this.colors = ["red","blue","green"];}SuperType.prototype.sayName = function(){alert(this.name);};function SubType(name,age){SuperType.call(this,name);this.age = age;}inheritPrototype(SubType,SuperType);SubType.prototype.sayAge = function(){alert(this.age);};var subType1 = new SubType("mary",20);var superType1 = new SuperType("aa",22);subType1.colors.push("element");superType1.colors.push("hhe");subType1.sayAge();subType1.sayName();console.log(subType1 instanceof SubType);console.log(subType1 instanceof SuperType);console.log(subType1.colors);console.log(superType1.colors);console.log(subType1.constructor == superType1.constructor);</script></body></html>



0 0
原创粉丝点击