js原型和原型链笔试题

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

var arr = [];
console.log(arr instanceof Array); //true
console.log(typeof arr);          //object 无法判断是否是数组

  instanceof 具体用法可以翻看我的另一篇博客JS中的instanceof运算符

 

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

 

posted @   打遍天下吴敌手  阅读(398)  评论(1编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
点击右上角即可分享
微信分享提示