JavaScript学习3_继承
对于javascript来说根本没有继承、多态属性。我们只能通过原型类的prop的指向转换来模拟出类似集成的效果。
apply vs call
apply和call都是讲对应的方法绑定到对应的对象上。只是他们传入的参数有区别。
# apply var obj = { name : 'linxin' } function func(firstName, lastName){ console.log(firstName + ' ' + this.name + ' ' + lastName); } func.apply(obj, ['A', 'B']); // A linxin B obj.func('A','B')
# call var obj = { name: 'linxin' } function func(firstName, lastName) { console.log(firstName + ' ' + this.name + ' ' + lastName); } func.call(obj, 'C', 'D'); // C linxin D
注意: 1、在apply和call传入为null时,this默认指代的为windows。 2、在绑定之后,我们直接可以通过对象进行调用 3、对象调用call,相当于将指向对象的构造函数绑定到了当前对象上。
借用构造函数继承
function Person (name, age) { this.type = 'human' this.name = name this.age = age } function Student (name, age) { // 借用构造函数继承属性成员 Person.call(this, name, age) } var s1 = Student('张三', 18) console.log(s1.type, s1.name, s1.age) // => human 张三 18
属性拷贝继承(for-in)
function Person (name, age) { this.type = 'human' this.name = name this.age = age } Person.prototype.sayName = function () { console.log('hello ' + this.name) } function Student (name, age) { Person.call(this, name, age) } // 原型对象拷贝继承原型对象成员 for(var key in Person.prototype) { Student.prototype[key] = Person.prototype[key] } var s1 = Student('张三', 18) s1.sayName() // => hello 张三
原型继承
function Person (name, age) { this.type = 'human' this.name = name this.age = age } Person.prototype.sayName = function () { console.log('hello ' + this.name) } function Student (name, age) { Person.call(this, name, age) } // 利用原型的特性实现继承 Student.prototype = new Person() var s1 = Student('张三', 18) console.log(s1.type) // => human s1.sayName() // => hello 张三
组合继承(构造函数继承+原型继承)
这是我们常用的继承方式。
通过构造函数,实行属性继承。 通过原型继承,实现方法继承
function Person (name, age) { this.type = 'human' this.name = name this.age = age } Person.prototype.sayName = function () { console.log('hello ' + this.name) } function Student (name, age, score) { // 借用构造函数解决属性重复问题 Person.call(this, name, age) this.score = score; } // 利用原型的特性实现继承 Student.prototype = new Person() Student.prototype.eat=function(){ console.log("吃东西") } var s1 = Student('张三', 18, 100) console.log(s1.type) // => human s1.sayName() // => hello 张三