对象的原型和继承问题
JavaScript 对象可以从对象的原型(prototype)继承属性和方法,任何一个对象(除了Object.prototype的原型是null)具有原型,也可以作为其他对象的原型,称为原型链。
-
Object.getPrototypeOf(object)可以返回参数对象的原型,顺着原型,原型的原型一级一级找,找不到该属性的话返回undefined。
-
为什么?
var m2array=function(){};
var m1array=function(){};
m2array.prototype=m1array;
var s = new m2array();
s instanceof m1array() // false
constructor属性
- prototype对象有一个constructor属性,默认指向prototype对象所在的构造函数。prototype是在构造函数m中的,所以prototype.constructor指向prototype所在的构造函数m,实例m1是没有constructor属性的,顺着原型链找。
var m=function(){};
var m1=new m()
m.prototype.constructor===m //true
m1.constructor===m.prototype.constructor //true
- 可以判断实例是由哪个构造函数构造的;也可以直接instance.constructor.name知道构造函数的名字。
var m=function(){};
var m1=new m()
m1.constructor===m //true
m1.constructor===Array //false
3.直接通过实例来调用构造函数来构造新的实例
var m=function(){};
var m1=new m()
var m2 = new m1.constructor();
m2 instanceof m //true
instanceof
1.instanceof 检查左侧是否在右侧的原型链上,除了null,所有对象的instanceof Object都是true,只适用于对象,不适用其他原始数据类型
var m=function(){};
var m1 = new m();
m1 instanceof m //true
//等价于
m.prototype.isPrototypeOf(m1) //true
2.instanceof可以解决调用构造函数忘了加new的问题
function m(){
if(this instanceof m){
this.name="liming";this.age=19;
}
else return new m();
}
var s = m();
typeof s //object
继承
function Shape() {
this.x = 0;
this.y = 0;
}
Shape.prototype.move = function (x, y) {
this.x += x;
this.y += y;
console.info('Shape moved.');
};
function Rectangle() {
Shape.call(this); // 调用父类构造函数
}
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;
Rectangle.prototype.method=function()
{
return this.x+this.y;
}
var s=new Rectangle();
s.move(3,4);
s.method();