function foo() { 
  var a = 10; 
  function bar() { 
    a *= 2; 
  } 
  bar(); 
  return a; 
} 
在上面的例子中函数foo在内部定义了变量a和方法bar,在foo外部是无法访问到a和bar的,但是因为a和bar都定义在foo内部,但bar是可以访问到a的。那么有没有办法能在foo外部访问到bar呢,答案是有的,就是使用闭包。
复制代码 代码如下:
 
function foo() { 
  var a = 10; 
  function bar() { 
    a *= 2; 
    return a; 
  } 
  return bar; 
} 
var baz = foo(); // baz is now a reference to function bar. 
baz(); // returns 20. 
baz(); // returns 40. 
baz(); // returns 80. 
var blat = foo(); // blat is another reference to bar. 
blat(); // returns 20, because a new copy of a is being used. 
这就是在前面提到的javascript函数支持内部函数。内部函数bar可以访问私有变量a,函数foo又把内部函数bar抛出给baz,baz就可以访问到内部变量a了,这就实现了闭包。大家一看也就明白了,这样其实就实现了私有变量和方法。回到我们前面的book例子,实现如下:
复制代码 代码如下:
 
var Book = function(newIsbn, newTitle, newAuthor) { 
  // implements Publication 
  // Private attributes. 
  var isbn, title, author; 
  // Private method. 
  function checkIsbn(isbn) { 
    ... 
  } 
  // Privileged methods. 
  this.getIsbn = function() { 
    return isbn; 
  }; 
  this.setIsbn = function(newIsbn) { 
    if(!checkIsbn(newIsbn)) throw new Error('Book: Invalid ISBN.'); 
    isbn = newIsbn; 
  }; 
  this.getTitle = function() { 
    return title; 
  }; 
  this.setTitle = function(newTitle) { 
    title = newTitle || 'No title specified'; 
  }; 
  this.getAuthor = function() { 
    return author; 
  }; 
  this.setAuthor = function(newAuthor) { 
    author = newAuthor || 'No author specified'; 
  }; 
  // Constructor code. 
  this.setIsbn(newIsbn); 
  this.setTitle(newTitle); 
  this.setAuthor(newAuthor); 
}; 
// Public, non-privileged methods. 
Book.prototype = { 
  display: function() { 
    ... 
  } 
}; 
上述代码就实现了 isbn, title, author和checkIsbn的私有化,外部是决定不能直接访问到的。如需访问 isbn, title, author只能通过对象级的方法getTitle,setTitle...。比如要给isbn赋值,只能用theHobbit.setIsbn = '978-0261103283';,如果你还用theHobbit._isbn = '978-0261103283';,对不起要报错了。
好了,今天的内容就讲到这里了,希望对大家有帮助。
作者:下一站永远
您可能感兴趣的文章:
