一、使用Object创建对象
通过调用Object构造函数new一个Object对象,然后再给这个对象的每一个属性和方法进行赋值
var person1 = new Object();
person1.age = 38;
person1.name = '宋小宝';
person1.speak = function () {
console.log('大家好!我是'+this.name);
};
console.log(person1 instanceof Object);
console.log(person1);
person1.speak();
结果:
二、使用对象字面量创建对象
var person2 = {
age: 38,
name: '小沈阳',
speak : function () {
console.log('大家好!我是'+this.name);
}
};
console.log(person2 instanceof Object);
console.log(person2);
person2.speak();
结果:
三、通过工厂模式创建对象
工厂模式通过将对象的创建封装到一个方法中
function createPerson(age, name) {
var obj = new Object();
obj.age = age;
obj.name = name;
obj.speak = function () {
console.log('大家好!我是'+this.name);
}
return obj;
}
var person3 = createPerson(29, '小沈龙');
console.log(person3 instanceof Object);
console.log(person3);
person3.speak();
结果:
四、构造函数模式
function Person(age, name) {
this.age = age;
this.name = name;
this.speak = function () {
console.log('大家好!我是'+this.name);
}
}
var person4 = new Person(37, '周云鹏');
console.log(person4 instanceof Object, person4 instanceof Person);
console.log(person4);
person4.speak();
结果:
五、原型模式
function Person(age, name) {
Person.prototype.age = age;
Person.prototype.name = name;
Person.prototype.speak = function () {
console.log('大家好!我是'+this.name);
};
}
var person5 = new Person(36, '程野');
console.log(person5 instanceof Object, person5 instanceof Person);
console.log(Person.prototype);
person5.speak();
结果:
六、构造函数+原型组合模式
function Person(age, name) {
this.age = age;
this.name = name;
}
Person.prototype = {
constructor: Person,
speak:function () {
console.log('大家好!我是'+this.name);
}
}
var person6 = new Person(32, '丫蛋');
console.log(person6 instanceof Object, person6 instanceof Person);
console.log(person6, Person.prototype);
person6.speak();
结果:
七、class定义类
class Person{
constructor(age, name){
this.age = age;
this.name = name;
this.cry = function () {
console.log(name + 'is crying!');
}
}
speak(){
console.log('大家好!我是'+this.name);
}
}
var person7 = new Person(35, '沈春阳');
console.log(person7 instanceof Object, person7 instanceof Person);
console.log(person7, Person);
person7.speak();
结果:
继承
使用extends和super实现继承
class Person{
constructor(age, name){
this.age = age;
this.name = name;
}
speak(){
console.log('大家好!我是'+this.name);
}
}
class Child extends Person{
constructor(age, name, heigh){
super(age, name);
this.heigh = heigh;
}
printHeigh(){
console.log(this.name + '身高:' + this.heigh);
}
}
var child = new Child(18, '小明', 180);
child.speak();
child.printHeigh();