封装
三种方式:
工厂函数模式
构造函数模式
构造函数模式和原型结合
工厂函数模式代码示例
function factory(name){
var obj = new Object();
obj.name = name;
obj.sayName = function(){
console.log('my name is ' + this.name);
}
return obj;
}
var obj = factory("xpf");
console.log(obj);
obj.sayName();
输出结果:
![](https://img-blog.csdnimg.cn/20190903184133230.png)
遗留问题:
1、类型无法细分
2、函数会重复创建/破坏封装性
构造函数模式代码示例
function Person(name,age){
this.name = name;
this.age = age;
this.sayName = function(){
console.log(this.name);
};
}
var person1 = new Person("xpf",29);
输出结果:
![](https://img-blog.csdnimg.cn/20190903184756516.png)
解决类型细分问题
遗留问题:
函数会重复创建/破解封装性
构造函数模式和原型结合代码示例
function Dog(name,age){
this.name = name;
this.age = age;
}
Dog.prototype = {
constructor:Dog,
sayName:function(){
console.log('name is',this.name);
},
sayAge:function(){
console.log('age is',this.age);
}
}
var d = new Dog('test',12);
var d2 = new Dog('hello',1);
d.sayName();
d.sayAge();
d2.sayName();
d2.sayAge();
console.log(d);
输出结果:
![](https://img-blog.csdnimg.cn/2019090318561341.png)
属性保存在实例中,方法保存在实例的构造函数原型中
继承
原型链继承
借用构造函数
原型链继承
1、子构造函数的原型指向父构造函数的实例
2、继承一般写在子构造函数实例之前
代码示例:
function Dog(name,age){
this.name = name;
this.age = age;
}
Dog.prototype = {
constructor:Dog,
sayName:function(){
console.log('name is',this.name);
},
sayAge:function(){
console.log('age is',this.age);
}
}
var d = new Dog('test',12);
d.sayName();
d.sayAge();
console.log(d);
Person.prototype = new Dog();
Person.prototype.constructor = Person;
function Person(name,age,gender){
this.name = name;
this.age = age;
}
var p = new Person('xpf',23,'male');
p.sayName();
p.sayAge();
console.log(p);
输出结果:
![](https://img-blog.csdnimg.cn/20190903190154861.png)
借用构造函数
使用Dog.call(this,name,age);
代码示例
function Dog(name,age){
this.name = name;
this.age = age;
}
Dog.prototype = {
constructor:Dog,
sayName:function(){
console.log('name is',this.name);
},
sayAge:function(){
console.log('age is',this.age);
}
}
var d = new Dog('test',12);
d.sayName();
d.sayAge();
console.log(d);
Person.prototype = new Dog();
Person.prototype.constructor = Person;
function Person(name,age,gender){
Dog.call(this,name,age);
}
var p = new Person('xpf',23,'male');
p.sayName();
p.sayAge();
console.log(p);
输出结果:
![](https://img-blog.csdnimg.cn/20190903190500544.png)