一、基于prototype原型
function Person(name){ this.name = name; } Person.prototype.eat="food"; function Student(name,eat){ Person.apply(this, arguments); } Student.prototype = new Person(); var s1 = new Student("王大", "food"); console.log(s1.name); console.log(s1.eat);
1、证明prototype模版并不是被拷贝到实例化的对象中,而是一种链接的方式,请看如下代码:
function Person(name, sex) { this.name = name; this.sex = sex; } Person.prototype.age = 20; var zhang = new Person("ZhangSan", "man"); console.log(zhang.age); // 20 // 覆盖prototype中的age属性 zhang.age = 19; console.log(zhang.age); // 19 delete zhang.age; // 在删除实例属性age后,此属性值又从prototype中获取 console.log(zhang.age); // 20