这里有一份简洁的前端知识体系等待你查收,看看吧,会有惊喜哦~若是以为不错,恳求star哈~javascript
// 字面量建立对象
var o1 = {name = "o1"};
var o2 = new Object({name : "o2"});
------------------------------------------
// 构造函数建立对象
var M = function () {
this.name = "o3";
}
var o3 = new M();
------------------------------------------
// Object.create建立对象
var p = {name : 'o4'};
var o4 = Object.create(p);
复制代码
注:咱们能够经过hasOwnProperty方法来判断一个属性是否从原型链中继承而来。前端
instanceof是原型链继承中的重要环节,对instanceof的理解有利于理解原型链继承的机制。java
以A instanceof B为例git
简单理解就是沿着A的__proto__跟B的prototype寻找,若是能找到同一引用,返回true,不然返回false。github
如下是一些示例:函数
// 因为函数也是对象,对象是函数建立的,因此有:
fn.__proto__ === Function.prototype
Object.__proto__ === Function.prototype
------------------------------------------
// Function是自身建立的,因此有:
Function.__proto__ === Function.prototype
------------------------------------------
// Function.prototype也是对象,因此有:
Function.prototype.__proto__ === Object.prototype
------------------------------------------
function Person() {}
console.log(Object instanceof Object); //true
//第一个Object的原型链:Object=>Object.__proto__ => Function.prototype=>Function.prototype.__proto__=>Object.prototype
//第二个Object的原型:Object=> Object.prototype
console.log(Function instanceof Function); //true
//第一个Function的原型链:Function=>Function.__proto__ => Function.prototype
//第二个Function的原型:Function=>Function.prototype
console.log(Function instanceof Object); //true
//Function=>
//Function.__proto__=>Function.prototype=>Function.prototype.__proto__=>Object.prototype
//Object => Object.prototype
console.log(Person instanceof Function); //true
//Person=>Person.__proto__=>Function.prototype
//Function=>Function.prototype
console.log(String instanceof String); //false
//第一个String的原型链:String=>
//String.__proto__=>Function.prototype=>Function.prototype.__proto__=>Object.prototype
//第二个String的原型链:String=>String.prototype
console.log(Boolean instanceof Boolean); //false
//第一个Boolean的原型链:
Boolean=>Boolean.__proto__=>Function.prototype=>Function.prototype.__proto__=>Object.prototype
//第二个Boolean的原型链:Boolean=>Boolean.prototype
console.log(Person instanceof Person); //false
//第一个Person的原型链:
Person=>Person.__proto__=>Function.prototype=>Function.prototype.__proto__=>Object.prototype
//第二个Person的原型链:Person=>Person.prototype
复制代码
var new2 = function (func) {
var o = Object.create(func.prototype);
var k = func.call(o);
if (typeof k === 'object') {
return k;
} else {
return o;
}
}
复制代码