js——原型与原型链

模仿Java,给一个Point类,并且得到Point的三个对象。代码如下:

function Point (row, col) {
	this.setRow = function (row) {
		this.row = row ? row : 1;
	}

	this.setCol = function (col) {
		this.col = col ? col : 1;
	}

	this.getRow = function () {
		return row;
	}

	this.getCol = function () {
		return col;
	}

	this.toString = function () {
		return '(' + row + ', ' + col + ')';
	}

	this.setRow(row);
	this.setCol(col);
}

console.log("Point:", Point);
var point1 = new Point(2,2);
var point2 = new Point(3,4);
var point3 = new Point(4,5);
console.log("point1:", point1);
console.log("point2:", point2);
console.log("point3:", point3);

输出Point,用浏览器打开,在控制台可以看到Point的相关信息

若有如图红色圈圈出的<prototype>,说明Point确实是一个对象 ,而蓝色圈圈出的<prototype>则是Point对象的原型链。(point3也有其对应的<prototype>,截图没有截到)

原型链起作用的是:父子关系、 类和对象关系的instance关系、 实例。

 

如下图的方式表示出类和对象

执行以下代码,看执行结果,会发现结果point2是Complex类的实现对象,显然这是不对的。

function Complex() {

}

point2.__proto__ = Complex.prototype;
console.log("point1 instanceof Point:", point1 instanceof Point);
console.log("point2 instanceof Point:", point2 instanceof Point);
console.log("point1 instanceof Complex:", point1 instanceof Complex);
console.log("point2 instanceof Complex:", point2 instanceof Complex);

只要将对象类的原型链的指向改变,不再指向Point的原型,那么,Point的对象的instance关系就会发生改变。

所以,原型链应该指向所属类的原型             与上面代码对应的画出一个Point类及其三个对象。

从最上面的结果可以看出Point的原型链是function() 因此Point的原型链应该指向Function的原型    

console.log("Function:", Function);
console.log("Function.prototype === Point.__proto__:", Function.prototype === Point.__proto__);
console.log("Point instanceof Function:", Point instanceof Function);

从上面例子可以看出,Function即是对象,也是函数,也是类。回到主题,Fnction的原型链应该指向某个类的原型,但是拥有这个原型的类应该是什么类?我有个大胆的猜测Function的原型链指向的是自己,不妨做一下尝试:

console.log("Function.prototype === Function.__proto__:", Function.prototype === Function.__proto__);
console.log("Function instanceof Function:", Function instanceof Function);

任何一个类的原型链应该指向Function的原型,并且所有类的原型对象类型是相同的,是类类型Object。

Object本身所属类型是Function,且Object的原型对象应该指向null,而不是指向自己,因为此时的原型链到了Object原型的尽头,是末节点

console.log("Object.__proto__ === Function.prototype:", Object.__proto__ === Function.prototype);
console.log("Object.prototype.__proto__ === Object.prototype:", Object.prototype.__proto__ === Object.prototype);
console.log("Object.prototype.__proto__:", Object.prototype.__proto__);

所以最后的关系图如下;

从上图可总结出:所有类的原型链指向Function的原型对象,所有类的原型对象类型是相同的,是类类型Object,并且Object的原型对象指向null。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值