Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

手写 instanceof #43

Open
MaMaFish opened this issue Apr 20, 2021 · 0 comments
Open

手写 instanceof #43

MaMaFish opened this issue Apr 20, 2021 · 0 comments

Comments

@MaMaFish
Copy link
Owner

MaMaFish commented Apr 20, 2021

instanceof 就是在实例的原型链中寻找构造函数的 Prototype

function myInstanceof(instance, constructer) {
    if (typeof instance !== 'object') {
        return false
    }
    while(true) {
        if (instance === null) {
            return false
        }
        if (instance.__proto__ === constructer.prototype) {
            return true
        }
        instance = instance.__proto__
    }
}

function Person (name) {
    this.name = name
}
const p1 = new Person('luo')
console.log(myInstanceof(p1, Person)) // true
console.log(myInstanceof(p1, Object)) // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant