JS对象构造函数

93 阅读1分钟

1. new

function createSquare(width){
    let obj = Object.create(createSquare.squarePrototype)
    obj.width = width
    return obj
}
createSquare.squarePrototype = {
    getArea(){ 
        return this.width * this.width 
    },
    getLength(){
        return this.width * 4
    }
    constructor: createSquare
}
let square = createSquare(5)

上面的代码被简化为下面的代码,唯一的区别是要用new来调用

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

1.1 总结

1.1.1 new X() 自动做了四件事情

  • 自动创建空对象
  • 自动为空对象关联原型,原型地址指定为X.prototype
  • 自动将空对象作为this关键字运行构造函数
  • 自动return this

1.1.2 构造函数X

  • X函数本身负责给对象本身添加属性
  • X.prototype对象负责保存对象的共用属性

1.2 ES6语法class

class Square{
    constructor(width){
        this.width = width
    } 
    getArea(){ 
        return this.width * this.width 
    }
}
class Square{
    static x = 1
    width = 0
    constructor(width){
        this.width = width
    } 
    getArea(){ 
        return this.width * this.width 
    }
    getLength(){
        return this.width * 4
    }
    get area2(){ // 只读属性
        return this.width * this.width
    } 
}

2. 原型公式

==对象.proto === 其构造函数.prototype==

2.1 JS终极一问

  • window是谁构造的

Window。可以通过constructor属性看出构造者

  • window.Object是谁构造的

window.Function。因为所有函数都是window.Function构造的

  • window.Function是谁构造的

window.Function。因为所有函数都是window.Function构造的。 浏览器构造了Function,然后指定它的构造者是自己

问题自测

26节

参考链接