我相信不少是看到这个标题进来看这篇文章的,那么会不会骂我标题党,哈哈,随意啦,文章内容重要,标题也是灵魂所在,因此拥有好的一个营销标题也是很是重要的。javascript
先来了解一下原型的基础知识点html
总结了以上几条规则后,我感悟最深的就是原来JS万物皆为NULL,真的是太深奥了。vue
咱们经过构造函数实例一个函数后,它内部的属性和方法只可以它本身用,其余实例没法共享到。为甚呢?java
例子面试
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
复制代码
prototype对象有一个constructor属性,默认指向prototype对象所在的构造函数bash
来一个例子微信
function Example(name){
this.name = name
}
Example.prototype.constructor === Example //true
复制代码
有什么做用呢函数
经常使用的做用就是constructor能够得知某个实例的对象,是由哪个构造函数产生的。例如:oop
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
![]()
![]()
参考文章