JS函数

1.0 工厂模式
function createPerson(name,age){
    let obj  = new Object()
    obj.name = name ;
    obj.age = age;
    obj.sayName=function(){
        console.log(this.name)
    }
    return obj
}
let person = createPerson('lili',23)
console.log(person) //{ name: 'lili', age: 23, sayName: [Function] }
console.log(person.sayName()) //lili 
2.0 构造函数模式
function CreatePerson(name,age,job){
    this.name = name ;
    this.age = age;
    this.job = job;
    this.sayName = function(){
        console.log(this.name)
    }
}
let person  = new CreatePerson('lisa',29,'dancer')
console.log(person.name,person.age,person.job) //lisa 29 dancer
console.log(person.sayName()) //lisa
3.0 原型模式
function CreatePerson(){}
    CreatePerson.prototype ={
        name :'NANA',
        age :'29',
        job:'sing',
        sayName : function(){
            console.log(this.name)
        }
    }
let person = new CreatePerson()
console.log(person.name,person.age,person.job) //NANA 29 sing
console.log(person.sayName()) //NANA  
4.0 构造函数 + 原型模式
function CreatePerson(name,age,job){
    this.name = name;
    this.age = age;
    this.job = job;
}
CreatePerson.prototype={
    sayName : function(){
        console.log(this.name)
    }
} 
let person1  = new CreatePerson('LALA',30,'dancer')
console.log(person1.name,person1.age,person1.job) //LALA 30 dancer
person1.name ="Dada"
console.log(person1.sayName()) //Dada    
let person2  = new CreatePerson('zhangsan',30,'dancer') 
console.log(person2.sayName()) //zhangsan

实例化构造函数时,返回的非对象将不生效

function People1 (){
    return 1
}
let person1 = new People1()
console.log(person1) //People1 {}
function People(){
    return {
        hello :'hi'
    }
}
let person = new People()
console.log(person) //{ hello: 'hi' }

你可能感兴趣的