- 伪类
通过构造函数产生对象
'use strict';
let Animal = function(name,age){
this.name = name;
this.age = age;
//以下定义方式不可访问
/*
let sysName = function(){
console.log(this.name)
}
*/
this.sysName = function(){
console.log(this.name)
}
}
let cat = new Animal('cat',10);
Animal.prototype.sysAge = function(){
console.log(this.age);
}
//cat.__proto__ === Animal.prototype
cat.__proto__.sysAll = function(){
console.log('name :'+ this.name+' age :'+ this.age);
}
cat.sysName();
cat.sysAge();
cat.sysAll();
let dog = new Animal('dog',5);
//加入到Animal.prototype的方法 dog都有
dog.sysName();
dog.sysAge();
dog.sysAll();
执行结果:
cat
10
name :cat age :10
dog
5
name :dog age :5
原理:
Function.method('new', function(){
//创建一个新对象
var that = object.create(this.prototype);
//调用构造器函数
var other = this.apply(that,arguments);
//如果other不是一个对象,返回that
return (typeof other === 'object' && other)||that;
//&&运算符如果左边为真,取右边值,否则,相反
//||运算符如果左边为正,取左边值,否则,相反
})
原型
let Animal = {
name :'animal',
age : 0,
sysName:function(){
console.log(this.name)
}
}
let cat = Object.create(Animal);
cat.name = 'cat';
cat.sysName();
执行结果:
cat
函数化
为建立对象增加私有变量和方法,利用变量。
'use strict';
let Animal = function(){
let name = 'animal';
let age = '5';
let that = {
getName : function(){
return name;
},
setName : function(str){
name = str;
return this;
}
}
return that;
}
var cat = Animal().setName('cat');
//只能通过getName()来访问name
console.log(cat.getName());
三种方法本质上都是基于原型的继承