1.函数声明
function test1(a){
a();
}
function test2(){
console.log("执行啦!");
}
test1(test2);//输出:"执行啦!"
2.函数表达式
var test=function(){
console.log("执行啦!");
}
test();//输出:"执行啦!"
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.构造函数模式
//首字母大写
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
//函数优化,避免内部函数重复创建
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
//原型对象.constructor=构造函数
//构造函数.prototype=原型对象
//实例对象=new 构造函数
//原型对象.isPrototypeOf(实例对象) true
6.组合构造函数模式和原型模式
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