const

原理:将其设置为window的属性时,重置其读写权限

function constFn(key, value) {
    window[key] = value
    Object.defineProperty(window, key, {
        enumerable: false,
        get() {
            return value
        },
        set() {
            throw new TypeError('Assignment to constant variable.')
        }
    })
}
constFn('name', 'hew')
name = 'new name'

call, apply

原理: 函数的 this 指向调用的对象

Function.prototype.myCall = function(_this, ...arg) { // 实现 apply 方法,这里不用加扩展符
    const anyFn = Symbol('anyFn') // 避免给对象添加的属性覆盖了已有的属性
    _this[anyFn] = this  // 给这个对象赋值当前调用的函数
    _this[anyFn](...arg) // 利用函数调用时 this 指向调用的对象;所以fn函数中的this指向了这里的_this
    delete _this[anyFn]
}
function fn(arg) { console.log(this.name) console.log(arg) }
const obj = { name: 'hew' }
fn.myCall(obj, '参数') 

bind


push

Array.prototype.push = function() {
    for (let i = 0; i < arguments.length; i++) {
        this[this.length] = arguments[i]
    }
    console.log('push');
    return this.length
}
Last Updated:
Contributors: Warren