JavaScript设计模式学习记录(二)

1.使用new实例化

原因:忘记加new的时候,式子右边函数会立即执行,然后变量获取的是函数的值,因为没有return,所以book是undefined

var Book = function(title, time, type){
    this.title = title;
    this.time = time;
    this.type = type;
}
//缺少new的实例化
var book = Book('javascript', '2018','js');
console.log(book);  //undefined

console.log(window.title);   //javascript
console.log(window.time);    //2018
console.log(window.type);    //js

//使用new来实例化
var book = new Book('javascript', '2018', 'js');
console.log(book);  //Book {title: "javascript", time: "2018", type: "js"}

2.为避免以上情况出现,可以创建对象的安全模式

var Book = function(title, time, type){
    if(this instanceof Book){
        this.title = title;
        this.time = time;
        this.type = type;
    }else{
        return new Book(title, time, type);
    }
}

var book = Book('javascript', '2018', 'js');
console.log(book);  //Book {title: "javascript", time: "2018", type: "js"}

猜你喜欢

转载自blog.csdn.net/qq_36414265/article/details/81776416
今日推荐