JavaScript创建对象与继承

来源:互联网 发布:牛丁手表怎么样知乎 编辑:程序博客网 时间:2024/05/07 08:13
/** * 原型式继承 */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

原创粉丝点击