logo头像

桃李不言,下自成蹊

JavaScript笔记整理第3篇

关于Javascript面向对象之继承
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
function Person(name,weight) {
this.name=name;
this.weight=weight;
}
Person.prototype.eat=function () {
console.log('作为一个人类,当然吃饭是此生第一大事');
}

function Student(love) {
this.love=love;
}
//通过改变原型指向实现的继承
Student.prototype = new Person('jack','50kg');
Student.prototype.study=function () {
console.log(this.name+'作为一个学生,要好好学习啊');
}

var stu = new Student('爱好唱歌');
console.log(stu.name,stu.weight);//调用父类的属性
stu.eat(); //调用父类的方法
stu.study();//调用自己的方法

/**
* 为了数据共享,改变原型指向,做到了继承------通过改变原型指向实现的继承
* 缺陷:改变原型指向的同事实现继承,直接初始化了属性,继承过来的值都一样了
* 只能重新调用对象属性进行重新赋值
*
*
*
* 解决方案:继承的时候,不用改变原型的指向,直接调用父级构造函数的方式为属性赋值就可以了-------借用构造函数:构造函数.call(当前对象,属性,属性,属性,属性....)
* 解决了属性继承,并且值不重复的问题
* 缺陷:父级类别的方法无法继承
*
*
*
* 组合继承:原型继承+借用构造函数两者都使用即实现了属性和方法的继承
* */
function Person(name,sex,age,height) {
this.name=name;
this.sex=sex;
this.age=age;
this.height=height;
}
Person.prototype.eat=function () {
console.log('饿了就要吃饭,天经地义的事儿!!!');
}

function Student(name,sex,age,height,score) {
//使用call方法,改变父类的this指向
Person.call(this,name,sex,age,height);
this.score=score;
}

var stu1 = new Student('jack','男',18,'180cm',180);
//stu1.eat(); 此处无发调用该方法,因为该方法没有被继承过来
console.log(stu1.name,stu1.sex,stu1.age,stu1.height,stu1.score);

var stu2 = new Student('rose','女',16,'170cm',280);
console.log(stu2.name,stu2.sex,stu2.age,stu2.height,stu2.score);
关于Javascript面向对象之拷贝继承
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
//拷贝继承:把一个对象中的属性或者方法直接复制到另一个对象中
var obj1={ //在堆里开辟内存空间
name:"jack",
sex:'男',
age:18,
}
//将obj1的内存地址赋值给obj2,只是改变了obj2的指向,两者实际上使用的是同一块内存空间
//var obj2 = obj1;
console.log(obj1 == obj2) //true
console.log(obj1 === obj2) //true

//拷贝继承
var obj1={ //在堆里开辟内存空间
name:"jack",
sex:'男',
age:18,
}
var obj2={}
for(var key in obj1){
obj2[key] = obj1[key];
}
console.log(obj1 == obj2) //false
console.log(obj1 === obj2) //false



//原型拷贝
function Person() {

}
Person.prototype.name='杰克';
Person.prototype.sex="男";
Person.prototype.height=100;
Person.play=function () {
console.log('我们可以一起玩吗');
}

var obj3 = {};
for(var key in Person.prototype){//浅拷贝:把一个空间的东西拷贝到另一个空间(在堆中)
obj3[key] = Person.prototype[key];
}
console.log(obj3);
console.dir(obj3.hasOwnProperty('sex'))//对象里边是否包含某个属性
支付宝打赏 微信打赏

您的支持是对作者最大的肯定