JS原型和原型链学习笔记

1.对应名称和从属关系

(1)对应名称

  • prototype:原型
  • __ proto__:原型链(链接点)

(2)从属关系

  • prototype -> 函数的一个属性:对象{}
  • __ proto__ -> 对象Object的一个属性:属性{}
  • 对象的__proto__保存着该对象的构造函数的prototype

2.认识原型和原型链

function Test(){
	this.a = 1;
};
console.log(Test.prototype);
Test.prototype.b = 2;
cosole.log(Test.prototype.__proto__ === Object.prototype);//true

const test = new Test();
console.log(test.__proto__);
console.log(Test.prototype === test.__proto__);//true

//Test.prototype = {__proto__}
console.log(Test.prototype.__proto__ === Object.prototype);//true
console.log(Object.prototype.__proto__);//null

Object.prototype.c = 3;

console,log(test);

上述代码的结构:

test{
	a:1,
	__proto__:Test.prototype = {
		b:2,
		__proto__:Object.prototype = {
			c:3,
			x __proto__
		}
	}
}

3.原型链继承

  • 在打印属性的时候,如果本身没有相关的属性,则会顺着原型链向上一级寻找 ,直到找到第一个相对应的值
console.log(test.a);//1
console.log(test.b);//2
console.log(test.c);//3

若更改示例代码的结构为:

test{
	a:1,
	b:222,
	__proto__:Test.prototype = {
		b:2,
		c:333
		__proto__:Object.prototype = {
			c:3,
			x __proto__
		}
	}
}

此时的打印结果为:

console.log(test.a);//1
console.log(test.b);//222
console.log(test.c);//333

4.Function与Object

  • Test()是由function构造出来的,那么它应该也有__proto__这个对象
  • //Object对象也是一个函数,Function的__proto__和prototype相等是底层规定好的
console.log(Test.__proto__ === Function.prototype);//true

console.log(Function.__proto__ === Function.prototype);//true

console.log(Object.__proto__ === Function.prototype);//true
console.log(Object.__proto__ === Function.Object);//true

5.判断属性是否存在

//判断对象上有没有该属性
console.log(test.hasOwnProperty('a'));//true
console.log(test.hasOwnProperty('b'));//false
console.log(test.hasOwnProperty('c'));//false
//判断对象的原型链上有没有该属性
console.log('a' in test);//true
console.log('b' in test);//true
console.log('c' in test);//true

6.constructor(构造函数)

console.log(test.constructor === Test);//true
//构造函数是可以更改的
function Test1(){
	this.a = 111;
}
test.cnostructor = Test1;
console.log(test);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值