js的继承探究(草稿)
果果o回忆吧
全部回复
仅看楼主
level 11
钟离小暖
楼主
2021年08月31日 04点08分
1
level 11
钟离小暖
楼主
原型链继承
首先原理确实是proto.proto
(发现改倒是可以改…… )
但是那些新增的对象怎么弄呢?
2021年08月31日 04点08分
2
level 11
钟离小暖
楼主
function Person(name, age) {
this.name = name,
this.age = age,
this.play = [1, 2, 3]
this.setName = function () { }
}
Person.prototype.setAge = function () { }// 在原型链新增的一个方法
//子类型
function Student(price) {
this.price = price
this.setScore = function () { }
}
var s=new Student(1);
s.__proto__.__proto__=Person;
console.log(s.__proto__.__proto__);
2021年08月31日 04点08分
3
level 11
钟离小暖
楼主
很神奇的说,其实理论上这样就可以了
关键点在区分函数和原型
s.__proto__是student创建的共享实例
p也是实例
但一定要s.__proto__.__proto__
function Person(name, age) {
this.name = name,
this.age = age,
this.play = [1, 2, 3]
this.setName = function () { }
}
Person.prototype.setAge = function () { }// 在原型链新增的一个方法
//子类型
function Student(price) {
this.price = price
this.setScore = function () { }
}
var s=new Student(1);
var p=new Person(1,2);
s.__proto__.__proto__=p;
console.log(s.__proto__.__proto__.play);
console.log(s.play)
2021年08月31日 04点08分
4
level 11
钟离小暖
楼主
然后看下老师怎么写的?
子类还是那个子类
父类还是那个父类
但是
既然没有实例来接 就直接用函数来接
直接把student共享的那一块给到person的一个实例,这样
【person里添加的也可以找两次共享到了】
Student.prototype = new Person('wang', 23) // 子类型的原型为父类型的一个实例对象
var s1 = new Student(15000)
var s2 = new Student(14000)
console.log(s1, s2) // console.log(s1.setAge) 这两个有上面setAge setScore~
2021年08月31日 05点08分
5
钟离小暖
【感觉最好要修个指向:Student.prototype.constructor=Student】
2021年08月31日 07点08分
钟离小暖
真坑啊,这老师不会又写错了吧
2021年08月31日 07点08分
level 11
钟离小暖
楼主
上面这原型链继承
1 只能继承一个父类
2 不能多重继承
3 而且会被共享
还有一种就是构造函数,
1 可传参 ,可以多重
2 不能复用,不能继承原型链新增的
function Person(name, age) {
this.name = name,
this.age = age,
this.setName = function () {}
}
function Student(name,age, price) {
Person.call(this,name, age)
// 相当于: 【也是因为这个,每个子元素都有父元素的一份拷贝】
/*
this.Person(name, age)
this.name = name
this.age = age
*/
this.price = price
}
var s1 = new Student('Tom', 20, 15000)
2021年08月31日 05点08分
6
level 11
钟离小暖
楼主
第三种
两者结合
既call了 又加了
Student.prototype = new Person()
Student.prototype.constructor = Student//组合继承也是需要修复构造函数指向的
2021年08月31日 05点08分
7
level 11
钟离小暖
楼主
es6的写法
首先函数分门别类constructor
其次继承要extends和super
之后就正常用就好了
2021年08月31日 05点08分
8
钟离小暖
【千万注意这里是class前缀】
2021年08月31日 10点08分
level 11
钟离小暖
楼主
最后记录口诀
es6的:
ces ESC!ESC然后就想到首先constructor 然后前面要extends 后面要super
ESCPro
正常的
pro
call
之前的
应表会传网数物
2021年08月31日 05点08分
9
level 11
钟离小暖
楼主
ESCPro
接下来希望手写实现一下
2021年08月31日 05点08分
10
level 11
钟离小暖
楼主
随便想了下,感觉es6的还可以
但是双重的不太会,那再去看一下
【毕竟到时候要实现的话,总的写个最全的吧】
下面是我自己手写的
1、第一个问题处理传入参数应该就是传入啥是啥而不是写默认的、?
其他的就ok了,可以很明显的感受到传参方便的多多多了
2021年08月31日 07点08分
11
level 11
钟离小暖
楼主
// self ------------------------------------------------------------
function son(name,age,cid) {
father.call(this,cid)
this.name=name;
this.age=age
}
function father(cid) {
this.cid=cid
}
son.prototype=new father();
son.prototype.constructor=son;
var s1=new son("Jimmy",14,9);
console.log(s1.name,s1.cid);
2021年08月31日 07点08分
12
1