面试

1.如何准确判断一个变量是数组类型

这里主要考察 typeof和instanceof,因为这里的确有坑

var arr = []
arr instanceof Array //true
typeof arr // Object typeof是无法判断是否是数组的

  

typeof

typeof用以获取一个变量或者表达式的类型,typeof一般只能返回如下几个结果:

    • number

    • boolean

    • string

    • function(函数

    • object(NULL,数组,对象)

    • undefined
      例如

      console.log(typeof (123));//输出:"number"
      console.log(typeof ("123"));//输出:"string"

       

 我们可以使用typeof来获取一个变量是否存在,如:

if(typeof a!="undefined"){
    //do something
}
//而不要去使用
if(a){
    //do something
}
//因为如果a不存在(未声明)则会出错,输出:Uncaught ReferenceError: a is not defined

typeof遇到数组,null,对象,都会返回Object

console.log(typeof(null))//"object"
console.log(typeof([]))//"object"
console.log(typeof({}))//"object"

所以当我们要判断一个对象是否是数组时,或者判断某个变量是否是某个对象的实例则要选择使用另一个关键语法instanceof

instanceof

instanceof用于判断一个变量是否某个对象的实例,如:

var arr=new Array();
console.log(arr instanceof Array);//true,
//因为Array是object的子类,所以
console.log(arr instanceof Object);//true,

  

再如:

function Foo(){};
var foo=new  Foo();
//foo 是Test的实例
console.log(foo instanceof  Foo)//true。

  

写一个原型链继承的例子

//创建Name构造函数
function Name() {
//为Name添加name方法
    this.name = function () {
        console.log("killua")
    }
}
//创建Firstname实例
function Firstname() {
//为Name添加firstname方法
    this.firstname = function () {
        console.log("L")
    }
}
//将Name的原型对象指向Firstname
Name.prototype = new Firstname();
//通过Name实例化一个对象he
var he = new Name();
console.log(he);
he.name(); //"killua"
he.firstname(); //"L"

  看下控制台输出:

name()为Name自有方法
调用he.firstname()时,js先查找Name是否有firstname方法,没有,继续沿着原型链查找,也就是he.__proto__,通过前几天的讨论我们知道he.__proto__===Name.prototype
然而Name.prototype = new Firstname(),所以从Firstname下找到了firstname方法

描述new一个对象的过程

  1. 创建一个新对象

  2. this指向这个新对象

  3. 执行代码,即对this进行赋值

  4. 返回this

 

//创建构造函数
function  Foo(name,age){
    //var this={};
    this.name=name;
    // return this;
}
Foo.prototype.alertName=function(){
    console.log(this.name);
}
//创建示例
var f=new Foo('zahngshan');
f.printName=function(){
    console.log(this.name);
};
//测试
f.printName();//zahngshan
f.alertName();//zahngshan

  

 

原型链

当试图得到一个对象的某个属性时,如果这个对象本身没有这个属性,那么会去它的proto(即它的构造函数的prototype)中寻找,即

console.log(obj.__proto__ === Object.prototype);

  看下面的图片,两行代码

function Foo(){}
var f = new Foo()

  

 

posted @ 2018-11-08 20:33  粉色年华  阅读(134)  评论(0编辑  收藏  举报