this 指向

  1. // this 指向问题
  2. function fun() {
  3. var self = this;
  4. self.name = name||'default';
  5. return {
  6. show : function(){
  7. console.log(1, self.name)
  8. },
  9. setName: function (name) {
  10. self.name = name;
  11. return this;
  12. }
  13. }
  14. }
  15. var obj = fun()
  16. console.log(2, obj.setName('sdf').show())
  17. console.log(3, fun().show())

闭包

  1. // 闭包问题
  2. var addCount;
  3. function s1() {
  4. var count = 0;
  5. function s12() {
  6. console.log(count)
  7. }
  8. addCount = function() {
  9. count++;
  10. };
  11. return s12
  12. }
  13. var result1 = s1();
  14. var result2 = s1();
  15. addCount();
  16. result1();
  17. result2();