js实现继承的三种方式
构造继承
构造继承,改变this指向
Person.call(this, x, y)
//构造继承 call()
//目的:让学生去继承人的属性和方法(构造函数的属性和方法 原型上的属性和方法)
//创建构造函数Person
function Person(name, age) {
this.name = name
this.age = age
this.eat = function () {
console.log(this.name + '喜欢吃');
}
}
//设置原型上的属性和方法
Person.prototype.sex = '男'
Person.prototype.sleep = function () {
console.log('喜欢睡觉');
}
//创建构造函数Student
function Student(code, x, y) {
this.code = code
this.play = function () {
console.log(this.name + '玩');
}
//构造继承,改变this指向
Person.call(this, x, y)
}
//构造继承不能拿到人原型上的属性和方法
Student.prototype = new Person()
Student.prototype.height = 200
Student.prototype.love = function () {
console.log('喜欢搞对象');
}
//实例化Student
var stu = new Student(100, '小明', 18);
console.log(stu);
//学生构造函数的属性和方法
console.log(stu.code);
stu.play()
//学生原型上的属性和方法
console.log(stu.height);
stu.love()
//人构造函数的属性和方法
console.log(stu.name);
stu.eat()
//人原型上的属性和方法
console.log(stu.sex);
stu.sleep()
原型继承
让学生继承人的属性和方法
Student.prototype = new Person(‘小明’, 20);
//创建构造函数Person
function Person(name, age) {
this.name = name
this.age = age
this.eat = function () {
console.log('喜欢吃');
}
}
//原型上的属性和方法
Person.prototype.sex = '男'
Person.prototype.sleep = function () {
console.log('喜欢睡觉');
}
//创建构造函数Student
function Student(code) {
this.code = code
this.play = function () {
console.log('玩');
}
}
//让学生继承人的属性和方法
Student.prototype = new Person('小明', 20);
//设置原型对象上的属性和方法
Student.prototype.height = 200
Student.prototype.love = function () {
console.log(this.name + '喜欢搞对象');
}
//实例化Student对象
var stu = new Student(100)
//调用
stu.love()
stu.play()
console.log(stu.age);
stu.eat()
console.log(stu.sex);
stu.sleep()
拷贝继承
for in遍历
for (x in p) {
stu[x] = p[x]
}
var stu = new Student(100);
var p = new Person('小明', 18)
for (x in p) {
stu[x] = p[x]
}
console.log(stu);