JS——闭包

来源:互联网 发布:韩美林 知乎 编辑:程序博客网 时间:2024/06/11 03:03
//在函数外部读取函数内部的变量function c(){var a=1000;function x(){a++;console.log(a);}return x;}var rece=c();rece();rece=null;


<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Document</title><style>#test{width: 100px;height: 100px;background: red;}</style></head><body><div id="test"></div><script>function getId(id){return document.getElementById(id);}var test=function(){this.age=1;};test.prototype={constructor:test,name:"My Object",getName:function(){//闭包var that=this;getId('test').onclick=function(){//console.log(this.name);console.log(that.name);}}}var test1=new test();test1.getName();</script></body></html>


原创粉丝点击