如题,准备面试一次就看一次,索性自己好好总结一下吧,一劳永逸。 javascript栏目从以下几个方面着手 0怎么理解面向对象 1创建对象的方式 2记住原型链的小窍门 3instanceof 模...
javascript栏目介绍面试必会的原型和继承
本文从以下几个方面着手
0 怎么理解面向对象其实我也不知道咋回答这问题,我只知道,面试官问这个后,就表示他要问一堆继承的问题了。下面是引用周老师的一段说辞。 "面向对象是一种编程思想 与面向过程是对应的 一般的语言都是面向对象的 js本身也是基于面向对象构建出来的 ,例如 js本身就有很多内置类,Promise就是,可以new Promise来创建一个实例,来管理异步编程 。 还有vue 也是,平时都是创建vue的实例啊。" 1 创建对象的方式1.对象字面量 var o1 = {name: 'o1'}
var o2 = new Object({name: 'o2'})2.通过构造函数 var M = function(name){
this.name = name
}
var o3 = new M('o3')3.Object.create var o4 = Object.create(p) 2 记住原型链的小窍门
3 instanceof 模拟实现instanceof 的原理是什么呢? 先来看一下使用 [] instanceof Array // true 即左边是对象,右边是类型,instanceof 就是要判断右边类型的prototype,是否在左边实例的原型链上,如下例子所示 [].__proto__ === Array.prototype //true Array.prototype.__proto__ === Object.prototype //true Object.prototype__proto__ //null
function myInstanceof2(left, right){
if(left === null || left === undefined){
return false
}
if(right.prototype === left.__proto__) {
return true
}
left = left.__proto__
return myInstanceof2(left, right)
}
console.log(myInstanceof2([], Array))4 new 模拟实现(简要版)
5 继承的实现(逐步实现)
function Parent3(){
this.name = 'Parent3'
this.arr = [1,2]
}
Parent3.prototype.say = function () {
alert('say')
}
function Child3(){
Parent3.call(this)
this.type = 'type'
}
Child3.prototype = new Parent3()
var c31 = new Child3()
var c32 = new Child3()
c31.say()
c31.arr.push('9')
console.log('c31.arr : ', c31.arr)
console.log('c31.arr : ', c32.arr)
改变上例子 的 Child3.prototype = new Parent3() 为 Child3.prototype = Parent3.prototype
为 Child3.prototype = Object.create(Parent3.prototype)
console.log(c31 instanceof Child3) // true console.log(c31 instanceof Parent3) // true console.log(c31.constructor === Child3) // false console.log(c31.constructor === Parent3) // true
function Parent3(){
this.name = 'Parent3'
this.arr = [1,2]
}
Parent3.prototype.say = function () {
alert('say')
}
function Child3(){
Parent3.call(this)
this.type = 'type'
}
Child3.prototype = Object.create(Parent3.prototype)
Child3.prototype.constructor = Child3
var c31 = new Child3()
var c32 = new Child3()
c31.say()
c31.arr.push('9')
console.log('c31.arr : ', c31.arr)
console.log('c31.arr : ', c32.arr)
console.log('c31 instanceof Child3 : ', c31 instanceof Child3)
console.log('c31 instanceof Parent3 : ', c31 instanceof Parent3)
console.log('c31.constructor === Child3 : ', c31.constructor === Child3)
console.log('c31.constructor === Parent3 : ', c31.constructor === Parent3)5 es6的继承 class Parent{
constructor(name) {
this.name = name
}
getName(){
return this.name
}
}
class Child{
constructor(age) {
this.age = age
}
getAge(){
return this.age
}
}es6继承记住几个注意事项吧
<figcaption></figcaption> 注意写了extends关键字,constructor中就必须写
以上就是javascript原型和继承是面试必会的的详细内容,更多请关注模板之家(www.mb5.com.cn)其它相关文章! |
