在理解对象中了解到了两种最简单的建立对象的方式,本篇详细讨论Js中各类建立对象的方法。javascript
重点须要搞清楚构造函数模式、原型模式和组合使用两种模式的建立对象实例方法。(明白前两个其实大概就明白了如何组合使用)html
工厂模式是一种普遍使用的设计模式, 建立对象的工厂模式,简单地理解就是将new Object()
建立对象的具体过程封装为一个函数前端
function CreatSomething(){
const o = new object();
o.propertyName1='value1';
o.propertyName2='value2';
...
o.functionName=function (){
console.log(this.propertyName1);
}
}
复制代码
工厂模式存在的问题是,没有解决对象识别的问题(没法判断一个对象是由哪一个函数实例化的),所以用的也很少,做为一个了解。java
经过Js的一些内置对象能够建立对象实例,如Object
、Array
等,也能够自定义构造函数,如:设计模式
funtion Something(val,num){
this.propertyName1=val;
this.propertyName2=num;
...
this.functionName=function (){
console.log(this.propertyName1);
}
}
const something1=new Something('val1',21);
const something2=new Something('val2',20);
复制代码
与工厂模式的区别在于:浏览器
new
承包了) ...=new Object()
this
对象return
新对象因此相比工厂模式,使用构造函数建立对象实例更简洁,高效。bash
那么,构造函数是如何将属性和方法赋给实例对象的呢?
关键在于:app
new 操做符
this
指针、做用域等相关知识点,参考this、apply、call、bind。对于new
操做符,我以为理解下其执行步骤,应该就清楚了函数
this
绑定到这个新建立的对象)补充:模拟一个new操做符的实现(建议了解清楚原型以后再回过头来看)oop
function myNew(func){
const objNull={}; //新对象
if (func.prototype !== null){
obj.__proto__=func.prototype;
}
const obj=func.apply(res,Array.prototype.slice.call(arguments,1)); //绑定this
if ((typeof obj === "object" || typeof obj === "function") && obj !==null){
return obj;
}
return objNull;
}
复制代码
在StackOverflow查阅new的时候看到一个评论戳中笑点...
简单来讲,构造函数的问题在其对象的方法上。
咱们建立的每个函数都有一个prototype
指针,指向一个对象(即原型对象),包含由当前函数派生出的全部实例共享的属性和方法。
当调用构造函数建立实例后,实例内部将会包含一个[[prototype]]
指针(浏览器中的实现是__proto__
),指向其构造函数的原型对象prototype
因此简单总结下,
.__proto__
=构造函数.prototype
Object.getPrototypeOf(
实例)==
构造函数.prototype
function Person(){...}
const someone=new Person();
someone.__proto__===Person.prototype //true
Object.getPrototypeOf(someone)===Person.prototype //true
复制代码
function Person(){
}
Person.prototype.property1=val1;
Person.prototype.property2=val2;
Person.prototype.funcName=function (){
console.log(this.property1)
};
const someone = new Person();
someone.fucName() // 输出val1
复制代码
Object Array Date RegExp FUnction
基本包装类型
Boolean Number String
单体内置对象
Global Math
复制代码
对象中值为引用类型的属性会被各实例共享,也就是说在原型模式下,改变一个实例对象的 引用类型属性值会影响到其余全部实例对象。
此处应该有个小结,不过还没想好该写些什么。
水平有限,不许确的地方,欢迎指正。
参考: