一般会问的问题:
创建对象有几种方法
原型关系
基于原型的执行规则
原型、构造函数、实例、原型链
通过原型链的方式找到原型对象,原型对象的方法是被不同的实例所共有的,这就是原型链的一个工作原理
1、构造函数(函数)才有propotype 的,对象没有 propotype,
2、只有实例对象有 __proto__的,函数既是函数又是对象
原型链
instanceof 原理:
实例对象的 __proto__ 和构造函数本身没有什么关联,它关联的是构造函数 prototype 下面的一个属性即 prototype 所引用的原型对象
是判断 实例对象.__proto__ 和 构造函数.prototype是不是一个引用(即引用同一个地址)
new 运算符
new 构造函数的原理:
生成一个空对象(Object.create)
将空对象的__proto__指向构造函数的prototype var o = Object.create(func.prototype)
执行构造函数,this 上下文指向空对象 var k = func.call(o)
若构造函数返回的是对象,那么这个对象将取代原来的空对象
if(typeof k === ‘object‘) {
return k
} else {
return o
}
题目
如何准确判断一个变量是不是数组?
答案:用 instanceof, 如 a instanceof Array
手写一个简易的 jQuery,考虑插件和扩展性
1 class jQuery { 2 constructor(selector) { 3 const result = document.querySelectorAll(selector) 4 const length = result.length 5 for(let i = 0; i < length; i++) { 6 this[i] = result[i] 7 } 8 this.length = length 9 this.selector = selector 10 } 11 get(index) { 12 return this[index] 13 } 14 each(fn) { 15 for(let i = 0; i < this.length; i++) { 16 const elem = this[i] 17 fn(elem) 18 } 19 } 20 21 on(type, fn) { 22 return this.each(elem => { 23 elem.addEventlistener(type, fn, false) 24 }) 25 } 26 } 27 28 jQuery.propotype.dialog = function(info) { 29 alert(info) 30 } 31 32 class myJQuery extends jQuery { 33 constructor(selector) { 34 supper(selector) 35 } 36 addClass(className) { 37 } 38 style(data) { 39 } 40 }
class的原型本质,怎么理解?
答案:
原文:https://www.cnblogs.com/queenya/p/13659441.html