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

大佬,有个小建议 #4

Closed
mrzqii opened this issue Sep 18, 2018 · 4 comments
Closed

大佬,有个小建议 #4

mrzqii opened this issue Sep 18, 2018 · 4 comments

Comments

@mrzqii
Copy link

mrzqii commented Sep 18, 2018

今天在学习插件的封装,所以研究了你的一些插件封装的思路,从你的代码里面获益匪浅,在这例发现一个问题,就是每次调用cookie()的时候都会去执行:

function Cookie() {
        if (!(this instanceof Cookie)) {
            return new Cookie();
        }
}

意味着每次都会创建一个新的实例,这样做在设计和性能方面都不是很好,我建议最好只创建一个实例就可以了。可以做如下改装:

function Cookie() { }
function init() {
        if ( !this.instance ){         
            this.instance = new Cookie();
        }     
        return this.instance; 
}

var cookie = function(name,value,option) {
        var arg = arguments;
        if(arg.length === 0) return init().all();
}

不知道我的思路怎么样?

@jaywcjlove
Copy link
Owner

jaywcjlove commented Sep 18, 2018

@mrzqii 开始有思考,有前途有进步

@jaywcjlove
Copy link
Owner

jaywcjlove commented Sep 18, 2018

if(!(this instanceof Cookie)) {
  return new Cookie()
};
``

这个就是防止重复 `new` 的判断

@mrzqii
Copy link
Author

mrzqii commented Sep 18, 2018

if(!(this instanceof Cookie)) {
  return new Cookie()
};
``

这个就是防止重复 `new` 的判断

没有起到作用哦:

把这里打一个log

if(!(this instanceof Cookie)) {
  console.log(1)
  return new Cookie()
};

然后调用:

<body>
    <script src="./cookie.js"></script>
    <script>
        cookie()
        cookie()
        cookie()
    </script>
</body>

打印的log:
1
1
1

因为每次调用Cookie()的时候this都是指向window

@jaywcjlove
Copy link
Owner

@mrzqii 了解

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

2 participants