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);