JavaScript基本知识——初识__proto__、prototype、原型链

JavaScript基本知识——初识__proto__、prototype、原型链

一、基本概念

在JavaScript中变量类型分为两大类基本类型和引用类型,而基本类型中除Undefined、Null外都有相对应的对象类型,因为这两个在javascript中表示“无”,可参考阮一峰的日志。所有的对象类型都是Object的实例,Object.prototype属性和方法可以通过new实例化访问,故所有对象都具有Object实例的属性和方法,这就是原型链prototype实现的。
在这里插入图片描述
__proto__也称隐式原型链,该属性指向该对象的构造器函数的prototype对象,保证了对象在实例化时调用构造器函数,在其中可以访问prototype属性,所有定义的变量都有 __proto__属性,例如:
在这里插入图片描述 在这里插入图片描述
prototype原型链是一个对象,对象类型具有这个属性,该属性实质是指向一个对象地址,同时该实例化的对象共享了prototype原型链对象的属性和方法。原型对象也有一个constructor构造器属性,这个属性也是一个对象并指向原始构造函数。
在这里插入图片描述
在这里插入图片描述
原型链指向,Array—>Object—>null;Function—>Object—>null。对象属性的查找是一层层往顶级查找。
__proto__和prototype区别:所有变量都有__proto__属性,prototype只有构造器函数才有。

二、应用场景

  1. 例一:
function Animal(name){
   this.name = name;
}

Animal.prototype.name= function() {  
   console.log("this is a "+this.name);
}
var dog = new Animal("dog");
Animal.prototype={
   go:function(){
   	console.log(this.name+" is going");
   },
   name:function() {  
   	console.log("this is a "+this.name);
   }
}
var cat= new Animal("cat");
dog.name();         //this is a dog
dog.go();                  //dog.go is not a function
cat.name();         //this is a cat
cat.go();                   //cat is going

解释:prototype指向嘚瑟对象,可以重新指定。

  1. 例二:
var Fun=function(){};
Object.prototype.a=function(){
   console.log('a()')
};
Function.prototype.b=function(){
   console.log('b()')
}
Fun.prototype.c=function(){
   console.log('c()')
}
var fun=new Fun();
fun.a();   //a()
fun.b();   //fun.b is not a function
fun.c();   //c()
Fun.a();   //a()
Fun.b();   //b()
Fun.c();   //Fun.c is not a function

解释:fun的原型是Fun的对象类型,Fun的原型是函数类型,属于构造器函数类型。

3.例三:

var arr=[1,2,3];
console.log(arr instandof Array);    //true
console.log(Array instandof Object); //true

猜你喜欢

转载自blog.csdn.net/qq_29510269/article/details/88818043