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);
待学习文件: