以下代碼顯示了如何創(chuàng)建需要自己的自定義類型私人財(cái)產(chǎn)。
function Book(name) { //from w w w . j av a 2 s . co m
// define a variable only accessible inside of the Book constructor
var version = 1;
this.name = name;
this.getVersion = function() {
return versioin;
};
this.publishNewNewsion = function() {
version++;
};
}
var book = new Book("Javascript");
console.log(book.name); // "Javascript"
console.log(book.getVersion()); // 1
book.version = 2;
console.log(book.getVersion()); // 1
book.publishNewNewsion();
console.log(book.getVersion()); // 2
上面的代碼生成以下結(jié)果。
在所有實(shí)例之間共享私有數(shù)據(jù):
var Book = (function() {
// everyone shares the same version
var version = 1;
/*from ww w .j ava 2 s. com*/
function InnerBook(name) {
this.name = name;
}
InnerBook.prototype.getVersion = function() {
return version;
};
InnerBook.prototype.publishNewVersion = function() {
version++;
};
return InnerBook;
}());
var book1 = new Book("Javascript");
var book2 = new Book("CSS");
console.log(book1.name); // "Javascript"
console.log(book1.getVersion()); // 1
console.log(book2.name); // "CSS"
console.log(book2.getVersion()); // 1
book1.publishNewVersion();
console.log(book1.getVersion()); // 2
console.log(book2.getVersion()); // 2
上面的代碼生成以下結(jié)果。
更多建議: