构造函数复习
function F1(name,age){
this.name = name;
this.age = age;
}
f1.prototype.method1 = function(){
console.log("helloworld");
}
原生的js是没有继承的标准语句的,那么我们就需要找一种方法来继承
我们在这之前还要学习一下constructor,
function F1(name,age)
{
this.name = name;
this.age = age;
}
var a = new F1("张三",18);
//F1.prototype.constructor = F1;//true
//prototype对象的constructor指向为F1函数
//a.constructor ===F1;//true
//a对象本身没有constructor的属性,a就会去找原型链去找构造函数
继承的进行曲
function A(m,b){
this.m = m;
this.b = b;
}
a.prototype.methods = function(){
console.log(11);
}
function B(m,b){
A.call(m,b);
this.values = 1;
}
B.prototype = Object.create(A.prototype);
//将A的原型生成一个匿名对象,是B的prototype指向该匿名对象,
//防止prototype的重复,
//因为关于对象”=“是将引用地址给赋值,而不是分配了一个独立的内存空间,
//于是将会导致B与A殊途同归,A,B最终成为同一个类即构造函数。
B.prototype.constructor = B;
//我们知道,当prototype改变,constructor指向也会改变,
//而我们还要调用它所以我们必须将constructor赋还给它
ES6继承方式
复习ES6的设置类的方式
class A{
constructor(a,b){
this.a = a;
this.b = b;
}
toString(){
console.log("A");
}
}
如阮一峰老师所说
class Point {
constructor() {
// ...
}
toString() {
// ...
}
toValue() {
// ...
}
}
// 等同于
Point.prototype = {
constructor() {},
toString() {},
toValue() {},
};
//1.class 中不存在变量提升
class Point {}
//2.class 中存在name属性
Point.name // "Point"
//箭头函数 var f = v => v;
class Logger {
printName(name = 'there') {
this.print(`Hello ${name}`);
}
print(text) {
console.log(text);
}
}
const logger = new Logger();
const { printName } = logger;
printName(); // TypeError: Cannot read property 'print' of undefined
出现上述问题的原因是因为this只指向刚开始构造时生成的对象,而this之后就会指向undefined
//一个比较简单的解决方法是,在构造方法中绑定this,
//这样就不会找不到print方法了。
class Logger {
constructor() {
this.printName = this.printName.bind(this);
}
// ...
}
//另一种解决方法是使用箭头函数。
class Obj {
constructor() {
this.getThis = () => this;
}
}
const myObj = new Obj();
myObj.getThis() === myObj // true
继承
class B{
constructor(x,y){
this.x = x;
this.y = y;
}
}
class A extends B {
constructor(x, y, color) {
super(x, y); // 调用父类的constructor(x, y)
this.color = color;
}
toString() {
return this.color + ' ' + super.toString(); // 调用父类的toString()
}
}
版权声明:本文为m0_52362034原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。