1.函數(shù)聲明
function test1(a){
a();
}
function test2(){
console.log("執(zhí)行啦贷屎!");
}
test1(test2);//輸出:"執(zhí)行啦惫东!"
2.函數(shù)表達(dá)式
var test=function(){
console.log("執(zhí)行啦拳球!");
}
test();//輸出:"執(zhí)行啦驾孔!"
3.工廠模式
function createPerson(name, sex, age) {
var obj = new Object();
obj.name = name;
obj.sex = sex;
obj.age = age;
obj.sayName = function () {
console.log("My name is Tom");
};
return obj;
}
var p1 = createPerson('Tom', '男', 20);
var p2 = createPerson('Jack', '男', 21);
console.log(p1.name);//輸出:"Tom"
console.log(p2.name);//輸出:"Jack"
4.構(gòu)造函數(shù)模式
//首字母大寫
function Person(name,sex,age){
this.name=name;
this.sex=sex;
this.age=age;
this.sayName=function(){
console.log("My name is Tom");
}
}
var p1=new Person('Tom','男',20);
var p2=new Person('Jack','男',21);
console.log(p1.constructor===Person);//輸出:true
console.log(p1 instanceof Person);//輸出:true
console.log(p1.sex===p2.sex);//輸出:true
console.log(p1.sayName===p2.sayName);//輸出:false
//函數(shù)優(yōu)化稽鞭,避免內(nèi)部函數(shù)重復(fù)創(chuàng)建
function Person(name,sex,age){
this.name=name;
this.sex=sex;
this.age=age;
this.sayName=sayName;
}
function sayName(){
console.log("My name is Tom");
}
var p1=new Person('Tom','男',20);
var p2=new Person('Jack','男',21);
console.log(p1.sayName===p2.sayName);//輸出:true
p1.sayName();//輸出:"My name is Tom"
5.原型模式
function Person(){
}
var obj=Person.prototype;
obj.name='Tom';
obj.sex='20';
obj.sayName=function(){
console.log("My name is Tom");
}
var p1=new Person();
var p2=new Person();
console.log(p1.name);//輸出:"Tom"
console.log(p1.sayName===p2.sayName);//輸出:true
console.log(p1.prototype);//輸出:undefind
//原型對(duì)象.constructor=構(gòu)造函數(shù)
//構(gòu)造函數(shù).prototype=原型對(duì)象
//實(shí)例對(duì)象=new 構(gòu)造函數(shù)
//原型對(duì)象.isPrototypeOf(實(shí)例對(duì)象) true
6.組合構(gòu)造函數(shù)模式和原型模式
function Person(name,sex,age){
this.name=name;
this.sex=sex;
this.age=age;
this.friends=["zhangsan","lisi"];
}
Person.prototype={
constructor:Person,
sayName:function(){
console.log("My name is Tom");
}
}
var p1=new Person('Tom','男',20);
var p2=new Person('Jack','男',21);
p1.friends.push("wangwu");
console.log(p1.friends);//輸出:["zhangsan","lisi","wangwu"]
console.log(p2.friends);//輸出:["zhangsan","lisi"]
console.log(p1.sayName===p2.sayName);//輸出:true
7.class模式
class Person{
constructor(name,sex,age){
this.name = name;
this.sex = sex;
this.age = age;
}
sayName(){
console.log("My name is Tom");
}
}
var p1=new Person('Tom','男',20);
var p2=new Person('Jack','男',21);
console.log(p1.name);//輸出:"Tom"
console.log(p1.sayName===p2.sayName);//輸出:true