在微信公众号“前端大全”中看到了波同学的讲解面向对象、构造函数、原型与原型链等内容,之前对于这几个知识点有去理解与使用过,但大多是处于似懂非懂的阶段,会用而已。今天凑巧看到了波同学的讲解,就此记录。
Object definition
An unordered collection of attributes, whose attributes can contain basic values, objects, or functions. It consists of a series of unordered key-value pairs in javascript
//对象
var person = {
name: 'Tom',//基本值
age: 18,
getName: function() {
},//函数
parent: {}//对象
}
//创建对象
var obj=new Object();
var obj={};
//给创建的对象添加方法
var person={};
person.name="mon";
person.getName=function(){
return this.name;
}
var person={
name:"mon",
getName:function(){
return this.name;
}
}
//访问对象的属性和方法
person.name
person['name']
['name','age'].forEach(funciton(item){
console.log(person[item]);
})
Factory mode
Provide a model, and then copy the object we need through this model
var createPerson=function(name,age){
//声明一个中间对象,该对象就是工厂模式的模子
var o=new Object();
//依次添加我们需要的属性和方法
o.name=name;
o.age=age;
o.getName=function(){
return this.name;
}
return o;
}
//创建两个实例
var perTom=createPerson('Tom',20);
var perJake=createPerson('Jake',22);
//识别对象实例的类型
var obj={};
var foo=function(){
};
console.log(obj instanceof Object);//true
console.log(foo instanceof Function);//true
Constructor
1. Compared with ordinary functions, there is nothing special about constructors. The capitalization of the first letter is just a small convention to distinguish ordinary functions.
2. The new keyword makes the constructor have many characteristics different from ordinary functions. The process is as follows: ①Declare
an intermediate object ②Point
the prototype of the intermediate object to the prototype of
the constructor ③Point the this of the constructor to the intermediate object
④ Return the intermediate object, that is, return the instance object
//创建构造函数
var Person=function(name,age){
this.name=name;
this.age=age;
this.getName=function(){
return this.name;
}
}
//将构造函数以参数形式传入
function New(func){
//声明一个中间对象,该对象为最终返回的实例
var res={};
if(func.prototype!==null){
//将实例的原型指向构造函数的原型
res._proto_=func.prototype;
}
//ret为构造函数执行的结果,通过apply,将构造函数内部的this指向修改为指向res,即为实例对象
var ret=func.apply(res,Array.prototype.slice.call(arguments,1));
//当我们在构造函数中明确指定了返回对象时,那么new的执行结果就是该返回对象
if((type ret==="object"||typeof ret==="function")&&ret !=null){
return ret;
}
//如果没有明确指定返回对象,则默认返回res,这个res就是实例对象
return res;
}
//通过new声明创建实例
var p1=New(Person,'tom',20);//p1实际接收的是new返回的res,等效于var p1=new Person('tom',20);
console.log(p1.getName());
console.log(p1 instanceof Person);//true