Jimmy小站
小明也有大梦想 — 蒋明/铭javascript 的prototype(原型)属性与javascript继承
2016-06-24 / 前端开发笔记 / 3477 次围观 / 0 次吐槽1. javascript的构造函数,其中的成员变量与方法都是对 对象的每个实例独立。
function Person (name, age, job) { this.name = name; this.age = age; this.job = job; this.sayName = function(){ alert(this.name); } }
2. 原型模式(另一种构造方法),其中定义的成员变量和方法是静态的,对象的每个实例共有。但是其中的变量是无法修改的。如果通过对象修改该值,没有任何作用。如果对该对象的某一实例修改prototype中定义的变量,会给该实例新增一个独占的同名成员变量并赋值,实际上prototype里的变量是没有被修改的。
Person.prototype = { constructor:Person, type:"human", sayHi:function(){ alert(this.age); } } var p1 = new Person(); var p2 = new Person(); Person.type = "animal"; alert(p1.type); //human p1.type = "animal"; alert(p1.type); // animal alert(p2.type); // human
3. javascript的继承可以通过prototype赋值的方式传递给子类(通过原型链作为实现继承的方法:以一个父类的实例赋值给子类的prototype实现继承)
Student.prototype = new Person(); function Student (clas, grade) { this.clas = clas; this.grade = grade; } var stu1 = new Student("1", 89); stu1.age = 22; alert(stu1.age); //22 alert(stu1.grade); //89 alert(Object.keys(stu1)); // clas,grade,age alert(Object.keys(stu2)); // clas,grade alert(stu2.age); //undefined
4.这里说明,在子类继承的时候,父类的属性(不管是构造函数中的属性还是原型中的属性)都成了子类的原型属性,子类所有实例共享。同时在构造对象实例的时候,还无法给父类传递父类需要的参数,这有时候并不是我们想要的结果。所以有下面另一种继承方式【借用构造函数 或伪造对象 或 经典继承】。即在子类中使用call方法执行父类的构造方法,从而向子类中添加父类的成员变量与方法。
function Person (name, age, job) { this.name = name; this.age = age; this.job = job; this.sayName = function(){ alert(this.name); } } Person.prototype = { constructor:Person, type:"human", sayHi:function(){ alert(this.age); } } function Student (name, age, job, clas, grade) { Person.call(this, name, age, job); this.clas = clas; this.grade = grade; } Student.prototype.sayGrade = function(){ //alert(this.grade); console.log(this.grade); } var stu1 = new Student("jimmy", 22, "software","1", 89); var stu2 = new Student("jimmy2", 21, "software","2", 88); stu1.sayGrade(); stu1.age = 22; alert(Object.keys(stu1)); //name, age, job, sayName, clas, grade alert(Object.keys(stu2)); //name, age, job, sayName, clas, grade alert(stu2.age); //21
5. 但是 使用经典继承,原型对象的方法无法继承,必须是在父类的构造函数中的方法才能继承。因此,为了解决两者之间的矛盾,我们可以采取混合继承的方式。成员变量使用经典继承,方法使用原型链继承
function Person (name, age, job) { this.name = name; this.age = age; this.job = job; this.sayName = function(){ alert(this.name); } } Person.prototype = { constructor:Person, type:"human", sayHi:function(){ alert(this.age); } } function Student (name, age, job, clas, grade) { //继承属性 Person.call(this, name, age, job); this.clas = clas; this.grade = grade; } //继承方法 Student.prototype = new Person(); Student.prototype.constructor = Student; Student.prototype.sayGrade = function(){ alert(this.grade); console.log(this.grade); } var stu1 = new Student("jimmy", 22, "software","1", 89); var stu2 = new Student("jimmy2", 21, "software","2", 88); stu1.sayGrade(); stu1.sayHi(); //22
- 上一篇:Ubuntu14.04安装 flash
- 下一篇:javascript的闭包
本月热文
Copyright © Jimmy小站 Allrights Reserved.备案号:桂ICP备 15005996
额 本文暂时没人评论 来添加一个吧
发表评论