JS深入-原型与原型链


typeof判断数据类型

typeof操作符返回一个字符串,说明变量的数据类型。
number,string,boolean,undefined,object,function
值类型:数值,字符串,布尔值,undefined
引用类型:数组,对象,null,函数

实例:
var arr=[];
console.log(typeof arr);//返回object,无法判断引用类型的具体类型,这里要使用instanceof
console.log(arr instanceof Array);//true

instanceof

instanceof判断一个实例是否属于某种类型
instanceof可以在继承关系中用来判断一个实例是否属于它的父类型

原型

__proto__//隐式原型属性
prototype//显式原型属性
所有引用类型(数组、对象、函数),__proto__属性值指向它的构造函数的prototype属性值
var arr=[];
arr.a=100;
arr.b=200;
var obj={};
obj.a=100;
obj.b=200;
function fn(){};
fn.a=100;
fn.b=200;
console.log(arr.__proto__);
console.log(fn.prototype);
console.log(obj.__proto__===Object.prototype);

原型链

function Foo(name,age){
this.name=name;
}
Foo.prototype.alet=function(){
alert(this.name);
}
var f=new Foo(‘Tom’);
f.conn=function(){
alert(this.name);
}
f.conn();//直接执行的
f.alet();
console.log(f instanceof Foo);
console.log(f instanceof Object);

原型链继承

function Anu(){
this.eat=function(){
// alert(‘Tom’);
}
}
function Dog(){
this.bat=function(){
// alert(‘Gom’);
}
}
Dog.prototype=new Anu();
var has=new Dog();
has.bat();
has.eat();

new一个对象的过程

创建一个新对象,this指向这个对象,执行代码,即对this赋值,返回this。

function Hoo(name,age){
this.name=name;
this.age=age;
this.class=’class-1’;
//return this默认有这一行
}
var d=new Hoo(‘Tom’,30);
//var f1=new Hoo(‘lisi’,20)//创建多个对象


文章作者: COOL
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 COOL !
评论
  目录