js中实现继承的方式(4种)
1、修改原型对象的指向
<script> //人的构造函数 function Person(name, age, sex) { this.name = name; this.age = age; this.sex = sex; } //给人的原型添加eat方法 Person.prototype.eat = function () { console.log("吃饭"); } Person.prototype.sleep = function () { console.log("睡觉"); } //学生的构造函数 function Student(score) { this.score = score; } //通过修改Student原型的指向实现继承 Student.prototype = new Person("zs", 20, "男"); //继承之后给自己添加方法 Student.prototype.study = function () { console.log("学生学习"); } var student = new Student(30);3 //人的属性和方法 console.log(student.name); //zs console.log(student.age); //20 console.log(student.sex); //男 student.eat(); //吃饭 student.sleep(); //睡觉 //学生自己的属性和方法 console.log(student.score); //30 student.study(); //学习 //被继承的对象的实例对象不能调用继承者的属性和方法 var per = new Person("wb",50,"女"); per.study(); </script>
通过修改原型的指向实现的继承,虽然实现了继承,但是继承后的实例对象的属性值都是一样的(都是 zs,20,男),只有自己定义的属性值不一样。
2、apply或者call实现继承
<script> //人的构造函数 function Person(name, age, sex) { this.name = name; this.age = age; this.sex = sex; } //给人的原型添加eat方法 Person.prototype.eat = function () { console.log("吃饭"); } Person.prototype.sleep = function () { console.log("睡觉"); } //通过借用构造函数实现继承 function Student(name,age,sex,score){ //借用,传入的this是Student的实例对象 Person.call(this,name,age,sex); this.score = score; } //继承之后给自己添加方法 Student.prototype.study = function () { console.log("学生学习"); } var student = new Student("zs",18,"男",30); var student2 = new Student("wb",20,"女",40); </script>
使用这种方式实现的继承,不能继承父类的方法,只能继承父类的属性。
3、结合原型指向和call实现继承
<script> //人的构造函数 function Person(name, age, sex) { this.name = name; this.age = age; this.sex = sex; } //给人的原型添加eat方法 Person.prototype.eat = function () { console.log("吃饭"); } Person.prototype.sleep = function () { console.log("睡觉"); } //通过借用构造函数实现继承 function Student(name,age,sex,score){ //借用,传入的this是Student的实例对象 Person.call(this,name,age,sex); this.score = score; } //修改原型的指向,实现方法的继承 Student.prototype = new Person() //继承之后给自己添加方法 Student.prototype.study = function () { console.log("学生学习"); } var student = new Student("zs",18,"男",30); var student2 = new Student("wb",20,"女",40); </script>
4、拷贝继承(复制一份)
方式一
var obj1 = { age: 18, name: "hello", eat: function () { console.log("chichichi"); } } //通过这种方式只是让obj2指向了和obj1相同的一块地址空间,内存中只有这一块空间,并没有复制一份 var obj2 = obj1; console.log(obj2);
方式二
var obj1 = { age: 18, name: "hello", eat: function () { console.log("chichichi"); } } //这种方式是开辟了一块空间,然后将obj1的东西复制到了obj2中,内存中有两块内容相同的空间 var obj2 = {}; for (var key in obj1) { obj2[key] = obj1[key]; } console.log(obj2);
方式三
<script> function Person() { } Person.prototype.name = "name"; Person.prototype.age = 18; Person.prototype.eat = function () { console.log("chichi"); } // var obj2 = Person.prototype; //或者 var obj2 = {}; for (var key in Person.prototype) { obj2[key] = Person.prototype[key]; } console.dir(obj2); </script>