构造函数小记

182 阅读1分钟

new X 构造函数的作用:
1、自动构造一个空对象
2、空对象原型指向X.prototype
3、this来运行这个构造函数
4、return this

构造函数X:
1、X负责给对象添加自身属性
2、X.prototype保存对象的共有属性

你是谁构造的,你的原型就是谁的prototype属性对应的对象
对象.__proto__ === 构造函数.prototype


class语法
Class Square{
    constructor(width){
        this.width = width
    }
    getArea(){
        return this.width * this.width
    }
    getLength(){
        return this.width * 4
    }
}

prototype语法

function Square(width){
    this.width = width
}
Square.prototype.getArea = function(){
    return this.width * this.width
}
Square.prototype.getLength = function(){
    return this.width * 4
}