Web前端高频面试题解析(javascript篇)--- 每日十题(6)

1.JS中清空数组的方法

var arr=[1,2,3,4,5]

1.splice

影响原数组

  • 第一个参数:规定添加或者删除元素的位置;
  • 第二个参数:要删除元素的数量
var arr = [1, 2, 3, 4, 5]
arr.splice(0, arr.length)
console.log(arr)//[]

2.length

数组的长度

console.log(arr.length)//0
arr.length = 0
console.log(arr)//[]

3.赋值为[]

arr = []
console.log(arr)//[]

2.JS中如何实现继承

B继承于A,A是父类,B是子类;继承可以让字类具有父类的各种属性和方法

  • 类:汽车
  • 属性:颜色,轮胎,品牌
  • 轿车:后备箱
  • 货车:大货箱

1.实现方法:

1.原型链的继承

function Person () {
      this.name = 'Person'
      this.arr = [1, 2, 3]
}
// 通过实例化对象
// console.log(new Person())
function Child () {
      this.type = 'child'
}
Child.prototype = new Person()
// 原型属性
Child.prototype.age = 18
// 实例化对象
console.log(new Child().age)//拿age
console.log(new Child())
console.log(new Child().arr)//(3) [1, 2, 3]

2.原型链继承的弊端:

改变一个,也会影响另外一个。子类的实例对象使用的是同一个原型对象

function Person () {
      this.name = 'Person'
      this.arr = [1, 2, 3]
}
function Child () {
      this.type = 'child'
}
Child.prototype = new Person()
var c1 = new Child()
var c2 = new Child()
c1.arr.push(5)
console.log(c1)
console.log(c2);
// 使用的同一个原型对象,改变一个,另外一个也会改变

 

 3.构造函数继承

借用call,改变this指向

function Person () {
      this.name = 'Person'
      this.arr = [1, 2, 3]
}
function Child () {
      Person.call(this)//this指向实例对象
      this.type = 'child'
}
console.log(new Child());

 4.解决了原型的弊端

构造函数不能继承原型属性的方法和属性。

继承方式只能继承父类的实例属性和方法,不能继承原型属性或者方法。 

function Person () {
      this.name = 'Person'
      this.arr = [1, 2, 3]
}
// 构造函数不能继承原型属性的方法和属性
Person.prototype.age = 18

function Child () {
      Person.call(this)//this指向实例对象
      this.type = 'child'
}
console.log(new Child())
var c1 = new Child()
var c2 = new Child()
c1.arr.push(5)
console.log(c1)
console.log(c2);

5.组合继承

最常用

function Person () {
      this.name = 'Person'
      this.arr = [1, 2, 3]
}
// 定义一个age
Person.prototype.age = 18

function Child () {
      Person.call(this)
      this.type = 'child'
}

// 原型链的继承
Child.prototype = new Person()
// 需要自己指向自己
Child.prototype.constructor = Child
var c1 = new Child()//通过子类实例的
var c2 = new Child()
console.log(c1.constructor)//  function Person () --> Child () 
c1.arr.push(5)
console.log(c1)
console.log(c2);

待学习文件:

 https://cloud.tencent.com/developer/article/1991885

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值