您的位置:首页 > Web前端 > JavaScript

JavaScript创建对象与继承

2012-10-22 13:34 435 查看
/**
* 原型式继承
*/
function object(o) {
function F() {}
F.prototype = o;
return new F();
}

/**
* 寄生组合式继承
*/
function inheritPrototype(subClass, superClass) {
var prototype = object(superClass.prototype);
prototype.constructor = subClass;
subClass.prototype = prototype;
}

/**
* 动态原型模式 创建Person对象
*/
function Person(name) {
this.name = name;

if (typeof this.sayName !== "function") {
Person.prototype.sayName = function() {
alert("Hello " + this.name);
}
}
}

/**
* 动态原型模式 创建Student对象
*/
function Student(name, age) {
Person.call(this, name);
this.age = age;

if (typeof this.sayHello !== "function") {
Student.prototype.sayHello = function() {
alert("My name is" + this.name + ", and my age is " + this.age);
}
}
}

/**
* Student继承Person的方法
*/
inheritPrototype(Student, Person);

var student = new Student("Jobs", 20);
student.sayName(); // Hello Jobs
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: