usercount

随笔:JS对象无new构造原理

var myFun = function(words) {
    if (!(this instanceof myFun)) {
        return new myFun(words);
    }
    this.name = 'ws';
    this.say = function() {
        console.log(words);
    }
    console.log(words);return this;
}

强制在使用方法时为用户—》创建对象,无论从何种角度来使用myFun ,都会创建对象。

关键点在于this的作用于。

正常来讲不判断this实例的情况下,调用方法时this指向window。

posted @ 2017-03-03 22:43  坦荡  阅读(210)  评论(0编辑  收藏  举报