1. 程式人生 > 其它 >js原型和原型鏈筆試題

js原型和原型鏈筆試題

1、如何準確判斷一個變數是陣列型別?

var arr = [];
console.log(arr instanceof Array); //true
console.log(typeof arr);          //object 無法判斷是否是陣列

2、寫一個原型鏈繼承的例子

  //動物
    function Animal() {
        this.eat = function () {
            console.log('animal to eat!')
        }
    }
    //狗
    function Dog() {
        this.call = function () {
            console.log('dog call!')
        }
    }
    Dog.prototype = new Animal();
    //秋田
var qiutian = new Dog() qiutian.call(); //dog call! qiutian.eat();//animal to eat!

  可以看出qiutian是Dog的例項化物件,qiutian繼承了Dog的方法call()這一點是沒有疑問的,但是為什麼qiutian依然能正常使用eat()方法呢?這是因為我們把Dog的原型物件指向了Animal,從而繼承了Animal的方法eat(),當qiutian使用eat()方法時,它本身是沒有這個屬性的,但它會順著__proto__去它的原型物件找,顯然Dog也沒有,它會繼續順著Dog的原型物件找到Animal,發現Animal有這個屬性從而繼承它。

3、描述new一個物件的過程

   function Person(name,age) {
        this.name = name
        this.age = age
        this.class = 'class-1'
        //return this  //預設有這一行
    }
    var person = new Person('Andy',13);
  • 建立一個新物件

var person = new Person('Andy',13) 將引數傳進去,函式中的 this 會變成空物件

  • this 指向這個新物件

   this.name = name;this.age = age;this.class = 'class-1' 為賦值;return this 為實際的執行機制

  • 執行程式碼,即對 this 賦值

   return 之後賦值給 person ,person具備了 person.name = Andy、person.age = 13、f.class = 'class-1'

  • 返回this

4、原型鏈

//建構函式
    function Person(name) {
        this.name = name
    }
    Person.prototype.sayName = function () {
        alert(this.name)
    }
    //例項化物件
    var p = new Person('Andy');
    p.printName = function () {
        console.log(this.name)
    }
    //測試
    p.printName();
    p.sayName();
    p.toString();//null

  p.toString(),當這個物件沒有這個屬性的時候,去它自身的隱式原型中找,它自身的隱式原型就是它建構函式(Person)的顯式原型(Person.prototype)但顯式原型(Person.prototype)中並沒有 toString ;但顯式原型(Person.prototype)也是物件,也要在它的隱式原型中找,即在其建構函式(Object)的顯式原型中去找 toString.故要在 p._proto_(隱式原型)的._proto_(隱式原型)中找,為null