创建一个类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| var Book = function(name, id) { this.name = name; this.id = id; }
Book.prototype.showName = function() { console.log(this.name); } 或者 Book.prototype = { showName: function() { console.log(this.name); } }
var book = new Book('javascript红宝书', 1); book.showName();
|
平常我们说的一些对象的公有属性,私有属性,公有方法,私有方法,特权方法,静态属性,静态方法这么多的名词到底是什么
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| var Book = function(name, id) { var num = 1;
function checkId() {};
this.getName = function() {}; this.getId = function() {}; this.setName = function() {}; this.setId = function() {};
this.name = name; this.id = id;
this.show = function() {};
this.setName(name); this.setId(id); }
Book.isChinese = true;
Book.resetTime = function() { console.log('resetTime'); }
Book.prototype = { isJsBook: true, showName: function() {} }
var book = new Book('javascript红宝书', 1); book.showName();
|
这样一个Book 的类就创建好了, 但是从开始定义Book = function…开始到最后感觉整个类的相关的定义是分开的, 不是一个整体, 所以一般就用闭包来将代码封装到一块:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| var Book = (function (){ var bookNum = 0; function checkBook(name) {}; function _book(name, id) { var name, id; function checkId(id) {}; this.getName = function() {}; this.getId = function() {}; this.setName = function() {}; this.setId = function() {}; this.name = name; this.id = id; this.show = function() {}; } _book.prototype = { isJSBook: false, display: function() {} }; return _book; })()
|