重写整个原型链的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(); //errorObject.create()是创建一个空对象,而空对象的原型(__proto__)指向传进来的参数
总结:使用Object.create()是将对象继承到__proto__属性上
var test = Object.create({x:123,y:345}); console.log(test);//{}console.log(test.x);//123console.log(test.__proto__.x);//3console.log(test.__proto__.x === test.x);//truevar test1 = new Object({x:123,y:345});console.log(test1);//{x:123,y:345}console.log(test1.x);//123console.log(test1.__proto__.x);//undefinedconsole.log(test1.__proto__.x === test1.x);//falsevar test2 = {x:123,y:345};console.log(test2);//{x:123,y:345};console.log(test2.x);//123console.log(test2.__proto__.x);//undefinedconsole.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为
要想实现继承需改成如下
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
