怎样快速写一个让面试官满意的原型链

2019-03-05  本文已影响1人  i5yue

我相信很多是看到这个标题进来看这篇文章的,那么会不会骂我标题党,哈哈,随意啦,文章内容重要,标题也是灵魂所在,所以拥有好的一个营销标题也是非常重要的。

先来了解一下原型的基础知识点

五条原则需要牢记

总结了以上几条规则后,我感悟最深的就是原来JS万物皆为NULL,真的是太深奥了。

首先我们需要了解下prototype属性的作用

我们通过构造函数实例一个函数后,它内部的属性和方法只能够它自己用,其他实例无法共享到。为甚呢?

例子

function Animal(type,name) {
    this.name = name;
    this.type = type;
    this.tell = function() {
        console.log('hello')
    }
}
var dog = new Animal('dog','lunky');
var cat = new Animal('cat','miao');
dog.tell === cat.tell//false

那么该怎么共享这个tell呢。这时候原型对象就发挥它的作用了,如果我们在原型定义属性和方法,那么这个函数所有的实例就能够共享到在原型上定义的方法或属性。
例子说明

function Animal(type,name) {
    this.name = name;
    this.type = type;
}
var dog = new Animal('dog','lunky');
var cat = new Animal('cat','miao');
Animal.prototype.color = 'red';
dog.color === cat.color //true
其次需要了解下constructor属性

prototype对象有一个constructor属性,默认指向prototype对象所在的构造函数

来一个例子

function Example(name){
    this.name = name
}
Example.prototype.constructor === Example //true

有什么作用呢

常用的作用就是constructor可以得知某个实例的对象,是由哪一个构造函数产生的。例如:

function Example(name){
    this.name = name
}
var e = new Example('ha')
e.constructor === Example// true
e.constructor === Date// false

上面实例中我们就可以看出,e的构造函数是Example,而不是Date.

来一个贴近工作的例子

平时我们工作中用到原型的地方,主要是全局注册一些第三方插件的时候,比如我们平时用vue写了一个插件,实例化后然后通过Vue.prototype定义到原型链上后,再用Vue.use方法。那么我们就可以全局调用这个方法了。那么面向面试官的时候,怎么在几分钟内写一个比较好的例子呢。

//一段HTML走起 
 <div id='example'></div>

//JS
function ElemDom(id) {
    this.elemDom = document.getElementById(id)
};
//定义一个写入内容的方法
ElemDom.prototype.html = function(val){
    var tempElemDom = this.elemDom;
    if(val){
        tempElemDom.innerHTML = val;
        return this;//这里为什么要return this
    }else {
        return tempElemDom.innerHTML
    }
}
//定义一个事件
ElemDom.prototype.on = function(type,fn){
    var tempElemDom = this.elemDom;
    tempElemDom.addEventListener(type,fn);
    return this;
}

var divDom = new ElemDom('example');
divDom.html('<p>hello world</p>').on('click',function(){
  console.log('i am coming')
}).html('<h1>footer</h1>')

代码中return this 是为了使用方法时能够链式调用,是不是看到了JQ写法的感觉。上面的例子看似简单,但是面试过程中能够手动写出来,然后在逐步讲解对原型链的了解,那么对于面试官来说还是能够有较好的印象的。希望这篇简短的文章能够帮助到你。

如果大神您想继续探讨或者学习更多知识,欢迎加入QQ一起探讨:854280588 QQ

参考文章

上一篇 下一篇

猜你喜欢

热点阅读