JavaScript面向对象继承

1、函数的调用方式

既可以使用函数名+()的形式调用,也可以使用函数名+call()的形式调用;

两种调用方式的区别:1)小括号调用:如果向小括号中传参,则该参数一定是函数所需要的参数;2)call()调用:如果向call的小括号中传参,则参数一定是一个对象,call会把所调函数中的this指针指到该参数上。


打印出window;undefind*3

call和apply的区别:功能上一模一样;在用法上:apply在传递函数所需参数时,使用数组结构传递

// hello.call(per, 'hello', '12', 34);

// hello.apply(per, ['hello', '12', 34]);

2、原型链方式实现继承

function CreateAnimal(name,age){this.name = name;this.age = age;}

function CreatePerson(name,age,gender){this.gender = gender;}

//把父级的对象当做子级的原型对象,这样父级就和子级建立了联系(通过父级对象的__proto__属性):

CreatePerson.prototype = new CreateAnimal('zhangsan',18);

//因为父级对象下的constructor属性指向的是创造它的函数,但是原型对象的constructor属性又必须指向创造它的原型的构造函数:所以要修改constructor的指针指向。

CreatePerson.prototype.constructor = CreatePerson;

var per = new CreatePerson('zhangsan',18,'man');

console.log(per);

3、组合继承

组合继承:即为使用call/apply实现对实例属性的继承,使用原型实现对原型方法的继承

function CreateAnimal(name,age){this.name = name;this.age = age;}

CreateAnimal.prototype.sayHi = function(){alert('hello';)}

function CreatePerson(name,age,gender){CreateAnimal.call(this,name,age); this.gender = gender;}

CreatePerson.prototype = new CreateAnimal();

CreatePerson.prototype.constructor = CreatePerson;

CreatePerson.prototype.eatFoot = function () {alert('吃饭了');}

var per = new CreatePerson('zhengSan', 18, 'man');

// console.log(per.gender);

per.sayHi();


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容