js原型链理解

var friend = new Person(); 
Person.prototype.sayHi = function(){ 
 alert("hi"); 
}; 
friend.sayHi(); //"hi"(没有问题!)

重写整个原型链的prototype时,已经实例话的对象只能取之前的prototype对象。

function Person(){ 
} 
var friend = new Person(); 
 
Person.prototype = { 
 constructor: Person, 
 name : "Nicholas", 
 age : 29, 
 job : "Software Engineer", 
 sayName : function () { 
 alert(this.name); 
 } 
}; 
friend.sayName(); //error

 Object.create()是创建一个空对象,而空对象的原型(__proto__)指向传进来的参数

总结:使用Object.create()是将对象继承到__proto__属性上

复制代码
var test = Object.create({x:123,y:345});
console.log(test);//{}
console.log(test.x);//123
console.log(test.__proto__.x);//3
console.log(test.__proto__.x === test.x);//true

var test1 = new Object({x:123,y:345});
console.log(test1);//{x:123,y:345}
console.log(test1.x);//123
console.log(test1.__proto__.x);//undefined
console.log(test1.__proto__.x === test1.x);//false

var test2 = {x:123,y:345};
console.log(test2);//{x:123,y:345};
console.log(test2.x);//123
console.log(test2.__proto__.x);//undefined
console.log(test2.__proto__.x === test2.x);//false

new Object() 也就是具有构造函数的内置Object的实例,新创建的对象的__proto__属性会指向Object的prototype

 疑问

function SuperType(){ 
 this.colors = ["red", "blue", "green"]; 
} 
SuperType.prototype.x=1;
function SubType(){ 
 //继承了 SuperType 
 SuperType.call(this); 
} 
var instance1 = new SubType();


得到的instance1为

为什么SubType.prototype.__proto__是Object.prototype 而不是SuperType.prototype 且instance1.x为undefined

要想实现继承需改成如下

function SuperType(){ 
 this.colors = ["red", "blue", "green"]; 
} 
SuperType.prototype.x=1;
function SubType(){ 
 //继承了 SuperType 
 SuperType.call(this); 
} 
SubType.prototype=new SuperType();
SubType.constructor=SubType;
或者
SubType.prototype=Object.create(SuperType.prototype);
SubType.constructor=SubType;
var instance1 = new SubType();
原文地址:https://www.cnblogs.com/nanacln/p/11424830.html