创建实例对象的安全模式

我们在创建实例对象是,若忘了new

const Book1 = function (title, time, type) {
    this.title = title
    this.time = time
    this.type = type
}
const book1 = Book1("JavaScript", "2021", "js")

在浏览器中,下述执行会依次返回 undefined  JavaScript  2021  js

console.log(book1)
console.log(this.title)
console.log(this.time)
console.log(this.type)

因为没有new创建实例,相当于静态执行了Book1,this指向window, 其实是调用的window.title window.time window.type

所以可以设计一种安全模式, 防止忘了new

const Book2 = function (title, time, type) {
    if(this instanceof Book2){
        this.title = title
        this.time = time
        this.type = type
    } else {
        return new Book2(title, time, type)
    }
}

 

posted @ 2021-11-26 22:19  邢韬  阅读(38)  评论(0编辑  收藏  举报