JavaScript 对象分类

83 阅读1分钟

构造函数

可以构造出对象的函数

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
}
for(let i = 0; i<12; i++){
    squareList[i] = createSquare(widthList[i])
    console.log(squareList[i].constructor)
}

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)

总计

  • new X() 自动做了四件事情
    • 自动创建空对象
    • 自动为空对象关联原型,原型地址指定为 X.prototype
    • 自动将空对象作为 this 关键字运行构造函数
    • 自动 return this
  • 构造函数 X
    • X 函数本身负责给对象本身添加属性
    • X.prototype 对象负责保存对象的共用属性

代码规范

大小写

  • 所有构造函数(专门用于创建对象的函数)首字母大写
  • 所有被构造出来的对象,首字母小写

词性

  • new 后面的函数,使用名词形式
  • 如 new Person()、new Object()
  • 其他函数,一般使用动词开头
  • 如 createSquare(5)、createElement('div')

原型公式

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

数组对象

定义一个数组

  • let arr = [1,2,3]
  • let arr = new Array(1,2,3) // 元素为 1,2,3
  • let arr = new Array(3) // 长度为 3

数组对象的自身属性

  • '0' / '1' / '2' / 'length'
  • 注意,属性名没有数字,只有字符串

数组对象的共有属性

  • 'push' / 'pop' / 'shift' / 'unshift' / 'join'

函数对象

定义一个函数

  • function fn(x,y){return x+y}
  • let fn2 = function fn(x,y){return x+y}
  • let fn = (x,y) => x+y
  • let fn = new Function('x','y', 'return x+y')

函数对象自身属性

  • 'name' / 'length'

函数对象共有属性

  • 'call' / 'apply' / 'bind'

class 语法

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