JavaScript学习笔记——通过继承原型来创建对象P4-原型链:在编写继承原型的原型时,通过方法call优化构造函数、重用代码

背景问题

下面基于小狗原型创建表演犬原型(原型链)

/
///小狗原型//
function Dog(name, breed, weight) {
    this.name = name;
    this.breed = breed;
    this.weight = weight;
}

Dog.prototype.species = "Canine";
Dog.prototype.bark = function() {
	console.log(this.name + " says Woof!");
};
Dog.prototype.run = function() {
    console.log("Run!");
};

使用构造函数Dog创建新对象:
var fido = new Dog("Fido", "Mixed", 38);
/
///继承了小狗原型的表演犬原型/
function ShowDog(name, breed, weight, handler) {
	this.name = name;
	this.breed = breed;
	this.weight = weight;
	this.handler = handler;
}
// We want the ShowDog prototype to be a Dog instance
ShowDog.prototype = new Dog(); 

ShowDog.prototype.league = "Webville";
ShowDog.prototype.gait = function(kind) {
	console.log(kind + "ing");
};
ShowDog.prototype.groom = function() {
	console.log("Groom");
};
//修复属性constructor不正确的问题
ShowDog.prototype.constructor = ShowDog;

使用构造函数ShowDog创建新对象:
var scotty = new ShowDog("Scotty", "Scottish Terrier", 15, "Cookie");

构造函数ShowDog和构造函数Dog有重复的代码

function ShowDog(name, breed, weight, handler) {
	this.name = name;//重复
	this.breed = breed;重复
	this.weight = weight;//重复
	this.handler = handler;
}

解决方法:函数的内置方法call

消除重复代码的理念:DRY (Don’t Repeat Yourself,不要自我重复),所有厉害的程序员都这么说

虽然这个示例的代码很简单,但有些构造函数可能使用复杂的代码来计算属性的初始值。因此创建继承另一个原型的构造函数时,都不应重复既有的代码

任何函数都有一个内置方法call

改写代码,用Dog.call调用函数Dog

  • 第一个参数传入一个对象,该参数指定了Dog函数内的this将要指向的对象;
    ps. 这里之所以调用方法call,而不直接调用Dog,就是因为这样可以控制Dog函数内的"this"的值
  • 其余参数传递了Dog函数的所有实参

改写后,优化版的构造函数ShowDog代码如下:

function ShowDog(name, breed, weight, handler) {

	重用构造函数Dog中处理属性name、breed、weight的代码
	Dog.call(this,name,breed,weight);

	构造函数Dog不认识handler属性,仍需要单独处理
	this.handler = handler;
}

var scotty = new ShowDog("Scotty", "Scottish Terrier", 15, "Cookie");

call的工作原理

通过call调用函数与之前用构造函数创建新对象不同:

复习
对比之前的调用Dog创建新对象
var fido = new Dog("Fido", "Mixed", 38);
这里的new创建了一个空对象,对其属性赋值后,返回新对象

调用改写后的ShowDog创建新对象时
通过call调用DogDog.call(this,name,breed,weight);这里没用new运算符,由此调用Dog没有新对象产生,也不会返回任何对象,只是单纯执行Dog中给属性赋值的语句;那么,这是在给哪个对象的属性赋值呢?——正是参数this传入的那个对象
ps. 这里的参数this,指向的是运算符new新建的ShowDog对象(使用new ShowDog(...)创建新对象时,new设置this指向其新创建的空对象)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值