JavaScript队列
2018-01-06 19:14 更新
Javascript面向对象的设计 - Javascript的私人会员的构造函数
以下代码显示了如何创建需要自己的自定义类型私人财产。
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
上面的代码生成以下结果。
![](https://atts.w3cschool.cn/attachments/jimg/javascript_object_oriented/DESCRIPTION__194D4B891998B8672F7D.png)
例子
在所有实例之间共享私有数据:
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
上面的代码生成以下结果。
![](https://atts.w3cschool.cn/attachments/jimg/javascript_object_oriented/EXAMPLE__6751E6C936ACD7A09ED5.png)
以上内容是否对您有帮助:
更多建议: