首页 > 其他 > 详细

回答问题(2019-11-19)

时间:2019-11-19 12:57:16      阅读:83      评论:0      收藏:0      [点我收藏+]
 1. typeof运算符和instanceof运算符以及isPrototypeOf()方法的区别
      typeof检查的是基本数据类型,返回一个字符串;
      instanceof判断前者是否是后者的实例,实现原理是判断后者的原型对象是否在前者的原型链上,如果是基于原型链的继承,子类的实例instanceof父类也会返回true;
      isPrototypeOf()方法与instanceof原理相似,都是去检测原型链,isPrototypeOf(),判断当前的原型对象(prototype)是否在传入参数的原型链上面,如Person.prototype.isProtypeOf(person),若person是Person的实例,函数返回true。
  
 1 var a = ‘a‘;
 2 var b = null;
 3 var c;
 4 alert(typeof a); // String
 5 alert(typeof b); //Object
 6 alert(typeof c); //undefined 
 7 
 8 function Person1(name){
 9     this.name = name;
10 }
11 function Person2(name){
12     this.name = name;
13 }
14 var p1 = new Person1();
15 var p2 = new Person2();
16 alert(p1 instanceof Person1); //true
17 alert(p2 instanceof Person2); //ture
18 alert(p2 instanceof Person1); //flase
19 //因为自定义对象自动继承了Object对象
20 alert(p1 instanceof Object); //true
21 alert(p1 instanceof Object); //true
22 
23 alert(Person1.prototype.isPrototypeOf(p1)); //true
24 alert(Person1.prototype.isPrototypeOf(p2)); //flase
25 alert(Object.prototype.isPrototypeOf(p1)); //ture

 

2.call()和apply()的区别
     call()和apply()表示在特定的作用域调用函数(会改变传入函数的this值),两者作用相同,区别只是传入参数的方式不同,apply()接受两个参数,一个是在其中运行函数的作用域,一个是参数数组(可以使Array实例或arguments对象);而call()第一个参数不变,变化的是其余参数直接传给函数。

 1 function sum(num1,num2){
 2     return num1+num2;
 3 }
 4 function callSum1(num1,num2){
 5     //传入arguments对象
 6     //由于函数在全局作用域调用,传入this值就是传入window对象
 7     return sum.apply(this,arguments);
 8 }
 9 function callSum2(num1,num2){
10     //传入数组
11     return sum.apply(this,[num1,num2]);
12 }
13 alert(callSum1(10,10)); //20
14 alert(callSum2(10,10)); //20
15 
16 function callSum(num1,num2){
17     return sum.call(this,num1,num2);   
18 }
19 alert(callSum(10,10)); //20

 

 

3.==和===有什么区别?

     ===是全等,使用==使如果两者数据类型相同,则进行===,如果数据类型不同,则会进行一次数据类型的转换再比较;而使用===时,数据类型不同会直接返回false。

 4. 简述javascript中this的指向 

    哪个对象调用函数,函数里面的this就指向哪个对象,如对于普通函数来说,this指向window对象;对于对象中的函数,用对象的实例去调用,this会指向这个实例;对于构造函数的中的this,this指向调用这个构造函数的对象。

回答问题(2019-11-19)

原文:https://www.cnblogs.com/xiaoxb17/p/11888525.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!