JavaScript-面向对象
创建普通对象
对象就是普通名值对集合
方法1:
var obj = new Object();
方法2:
var obj = {
}
示例:
obj = {
name: {
first: 'Gandalf',
last: 'the Grey',
},
address: 'Middle Earth',
};
声明类
类属性
function Book(title, pages, isbn){
this.title = title;
this.pages = pages;
this.isbn = isbn;
}
类方法
方法1:原型声明
Book.prototype.printTitle = function(){
console.log(this.title);
};
原型方法printTitle只会创建一次,在所有实例中共享
方法2: 类中声明
function Book(title, pages, isbn){
this.title = title;
this.pages = pages;
this.isbn = isbn;
this.printIsbn = function(){
console.log(this.isbn);
}
};
类的定义中声明,则每个实例都会创建自己的函数副本
实例化类
var book = new Book('title', 'pig', 'isbn');