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

函数自定义属性 #32

Open
youngwind opened this issue Mar 1, 2016 · 0 comments
Open

函数自定义属性 #32

youngwind opened this issue Mar 1, 2016 · 0 comments
Labels

Comments

@youngwind
Copy link
Owner

情景

假设我们要完成这样一个需求:页面内有一个按钮和一个数字,每次点击这个按钮,数字都会加1。以前我是这样写的。

var num = 0;
function add(){
   num ++;
   return num;
}
$('btn').click(function(){
  $('#num').html(add());
});

需求抽象来描述应该是这样的:有一个变量A和函数B,变量A只会被函数B改变,其他的函数也会读取变量A,但是不会改变它。上面的做法虽然也可以,但是却引入了两个全局变量。明明num和add是一体的,为什么非得占用两个命名空间呢?这种情况可以用函数自定义属性来解决。

函数自定义属性

add.num = 0;
function add(){
   return ++add.num;
}
$('btn').click(function(){
  $('#num').html(add());
});

在js中,函数是一种特殊的对象,但它毕竟也是对象,可以拥有自己的属性值,这样就可以使命名空间更加整洁了。(PS:之所以一开始可以定义add.num = 0,那是因为函数声明被提升了。)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant