js闭包应用

前端开发 作者: 2024-08-25 21:55:01
先来看一个例子: 一直以来,我都是以为只有用匿名函数才能算是闭包,但是其实不一定要用匿名函数的,就是一般的函数就可以,前提是它得被包含在另一个函数中。 在foo返回后,它的作用域被保存下来了,但只有它
 function foo() {
      var a = 10;
     
       bar() {
        a *= 2;
        return a;
      }
       
       bar;      
    }

    var baz = foo(); // baz is now a reference to function bar.
    console.log(baz());  returns 20.
    console.log(baz());  returns 40.
    console.log(baz());  returns 80.

    var blat = foo();  blat is another reference to bar.
    console.log(blat());  returns 20,because a new copy of a is being used. 
var Book = function(newIsbn,newTitle,newAuthor) {  implements Publication

   Private attributes.
  var isbn,title,author;

   Private method.
   checkIsbn(isbn) {
    ... 
    return true;
  }  

   Privileged methods.
  this.getIsbn = () {
     isbn;
  };
  this.setIsbn = (newIsbn) {
    if(!checkIsbn(newIsbn)) throw new Error('Book: Invalid ISBN.');
    isbn = newIsbn;
  };

  this.getTitle =  title;
  };
  this.setTitle = (newTitle) {
    title = newTitle || 'No title specified';
  };

  this.getAuthor =  author;
  };
  this.setAuthor = (newAuthor) {
    author = newAuthor || 'No author specified' Constructor code.
  this.setIsbn(newIsbn);
  .setTitle(newTitle);
  .setAuthor(newAuthor);
};

 Public,non-privileged methods.
Book.prototype = {
  display: ...
  }
};


var mybook=new Book("myisbtn","mytittle","myauthor");
console.log(mybook.getAuthor());
View Code
var Book = (() {
  
   Private static attributes.
  var numOfBooks = 0;

   Private static method.
   checkIsbn(isbn) {
    ...
   ; 
  }    

   Return the constructor.
   implements Publication

     Private attributes.
     Privileged methods.
    () {
       isbn;
    };
    (newIsbn) {
      );
      isbn = newIsbn;
    };

     title;
    };
    (newTitle) {
      title = newTitle || 'No title specified';
    };

     author;
    };
    (newAuthor) {
      author = newAuthor || 'No author specified' Constructor code.
    numOfBooks++;  Keep track of how many Books have been instantiated
                   with the private static attribute.
    if(numOfBooks > 1) new Error('Book: Only 1 instances of Book can be '
        + 'created.');

    .setIsbn(newIsbn);
    .setTitle(newTitle);
    .setAuthor(newAuthor);
  }
})();

 Public static method.
Book.convertToTitleCase = (inputString) {
  ...
  console.log("convertToTitleCase");
};

...
    console.log("display");
  }
};



);
console.log(mybook.getAuthor());    myauthor
mybook.display();                   display
//mybook.convertToTitleCase();      //mybook.convertToTitleCase is not a function

var mybook2= new Book("my2","tittle2","myauthor2");
console.log(mybook2.getAuthor());   Only 1 instances of Book can be created.
View Code
原创声明
本站部分文章基于互联网的整理,我们会把真正“有用/优质”的文章整理提供给各位开发者。本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
本文链接:http://www.jiecseo.com/news/show_68620.html
js闭包应用