原型继承
代码如下:
// 目的:让学生继承人的属性和方法(构造函数的和原型上的)、
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(this.name + '喜欢睡觉')
}
function Student(code) {
this.code = code
this.play = function () {
console.log(this.name + '喜欢玩游戏')
}
}
Student.prototype.height = 100
Student.prototype.study = function () {
consoloe.log(this.name + '喜欢学习')
}
console.log(Student.prototype.constructor == Student)
Student.prototype = new Person('小明', 18)
// 将学学生原型的属性和方法放到继承里面
Student.prototype.height = 100
Student.prototype.study = function () {
console.log(this.name + '喜欢学习')
}
var stu = new Student(100)
console.log(stu)
// 学生构造函数的属性和方法
console.log(stu.code)
stu.play()
// 学生原型上的属性和方法
console.log(stu.height)
stu.study()
// 人构造函数的属性和方法
console.log(stu.name)
stu.eat()
// 人原型上的属性和方法
console.log(stu.sex)
stu.sleep()
构造继承
代码如下:
// 目的:让学生继承人的属性和方法(构造函数的和原型的)
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(this.name + '喜欢睡觉')
}
function Student(code, x, y) {
this.code = code
this.paly = function () {
console.log(this.name + '喜欢玩游戏')
}
Person.call(stu)
Person.call(this, x, y)
}
Student.prototype = new Person()
Student.prototype.height = 100
Student.prototype.study = function () {
console.log(this.name + '喜欢学习')
}
var stu = new Student(100, '小明', 18)
var p = new Person('小明', 18)
console.log(stu)
// 学生构造函数的属性和方法
console.log(stu.code)
stu.paly()
// 学生原型的属性和方法
console.log(stu.height)
stu.study()
// 人构造函数的属性和方法
console.log(stu.name)
stu.eat()
// 人原型的属性和方法
console.log(stu.sex)
stu.sleep
拷贝继承
代码如下:
// 目的:让学生继承人的属性和方法(构造函数的和原型的)
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(this.name + '喜欢睡觉')
}
function Student(code, x, y) {
this.code = code
this.play = function () {
console.log(this.name + '喜欢玩游戏')
}
}
Student.prototype.height = 100
Student.prototype.study = function () {
console.log(this.name + '喜欢学习')
}
var stu = new Student(100)
var p = new Person('小明', 18)
for (x in p) {
stu[x] = p[x]
}
console.log(stu)
// 学生构造函数的属性和方法
console.log(stu.code)
stu.play()
// 学生原型上的属性和方法
console.log(stu.height)
stu.study()
// 人构造函数的属性和方法
console.log(stu.name)
stu.eat()
// 人原型上的属性和方法
console.log(stu.sex)
stu.sleep()