//字面量的方式
var obj = {
name : "beijing",
age : 12,
showName : function(){
return this.name
},
hobbies : ["读","写","看"],
json : {
"adress" : "天津"
}
}
//构造对象
var obj = new Object();
obj.name = "张三";
obj.age = 21;
//工厂模式
function createObj(name,age){
var obj = new Object();
obj.name = name;
obj.age = 1;
return obj;
}
var dog1 = createObj("张三",12)
//构造函数(es5)
function Person(name,age){
//实例属性(创建在构造函数中的属性,都叫实例属性)
this.name = name;
this.age = age;
//实例方法(创建在构造函数中的方法,都叫实例方法)
this.showName = function(){
return this.name;
}
}
var ps1 = new Person("张三",18);
var ps2 = new Person("张三",19);
//原型
function Dog(){} //创建构造函数
//原型属性
Dog.prototype.name = "小黑";
Dog.prototype.age = 2;
//原型方法
Dog.prototype.showName = function(){
return this.name;
};
Dog.prototype.showAge = function(){
return this.age;
};
var dog1 = new Dog();
var dog2 = new Dog();
//混合模式
function Cat(name,age){
//实例属性
this.name = name;
this.age = age;
}
//原型方法
Cat.prototype.showName = function(){
return this.name;
};
Cat.prototype.showAge = function(){
return this.age;
};
var cat1 = new Cat("小花",4);
//cat1.name = "小黄";
console.log(cat1.showName());
//构造类(es6)
class Father{
constructor(name,age){
this.name = name;
this.age = age;
}
showName(){
return this.name;
}
}
var ps1 = new Father("北京");
console.log(ps1.name)
//继承
class Son extends Father{
//创建构造器
constructor(name,age,like){
//调用父类构造器,也成为超类,基类
super(name,age); //必须在第一行调用
this.like = like;
}
showLike(){
return this.like;
}
}
var son1 = new Son("张三",18,"弹钢琴");
console.log(son1.showLike());
console.log(son1.like)