Javascript中的应用和呼叫继承
申请和调用的区别
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
</body>
<!--其实申请和调用这两个方法基本上是差不多的,区别在于调用的第二个参数可以是任意类型,
而申请的第二个参数必须是数组,也可以是自变量(即传给构造函数的参数)-->
<!--例如我们把上面的代码稍微改一下,如果此时我在新的构造函数猫时候的参数传入new cat('wsscat','cute')我们的猫能接收参数,
但是如果此时继承是animal.call(this),没有给呼叫传第二个参数的时候,
生成的对象中类型的值就会是未定义的,所以为了让这个值能够让动物接收,
我们可以在动物中传入第二个参数animal.call(此,类型)-->
<script type="text/javascript">
function animal(type) {
this.type = type
this.behavior = function(){
console.log(this.type+" is running")
}
}
function cat(name, type) {
this.name = name
//这里call的意思就是把animal的方法应用到cat这个对象身上
//所以cat就继承了animal的方法
//animal.call(this);//type undefined
//animal.call(this,type);//type cute
//animal.call(this,arguments[1]);//type cute
//animal.call(this,arguments);//type ['wsscat','cute']
animal.apply(this,arguments)//type: wsscat
}
console.log(new cat('wsscat','cute'))
// 这里用适用就很方便,因为参数是数组,可以全部传给动物,而调用就要一个个地传过去
</script>
</html>
继承的优化
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<!--如果构造函数这个绑定太多属性(比如一些共同方法),在实例化后会造成浪费,
为此我们一般会使用原型链来优化,但是使用原型链之后我们的应用和呼叫的继承方法就会失效
为此我们一般使用混合的写法,使用原型链和(申请或者电话)进行方法继承
具体两句话
让子的原型链指向父的实例(父实例化的对象)
cat.prototype = new animal();
让父的属性创建在子的这个上
animal.call(this, type)
本世纪的牛顿代码如下,那么就会让父原型链的属性和该上的属性都得到继承-->
<script type="text/javascript">
function animal(type) {
this.type = type
this.behavior = function() {
console.log(this.type + " is running")
}
}
animal.prototype.action = function() {
console.log("running")
}
function cat(name, type) {
this.name = name
animal.call(this, type)
}
cat.prototype = new animal();
console.log(new cat('wsscat', 'cute'));
(new cat('wsscat')).action() //running
</script>
<body>
</body>
</html>
调用实现多重继承
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
</body>
<script type="text/javascript">
// 当然我们可以继承多个构造函数,这就是多重继承
function animal(a, b) {
this.type = 'animal'
this.behavior = function(){
console.log(this.type+" is running")
}
}
function wsscat(a, b) {
this.age = 0
}
function cat(a, b) {
this.name = 'wsscat'
//这里call的意思就是把animal的方法应用到cat这个对象身上
//所以cat就继承了animal的方法
animal.call(this);
wsscat.call(this);
}
console.log(new cat())
</script>
</html>
调用实现继承
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
</body>
<script type="text/javascript">
// 拨打电话这里的意思就是把动物的方法应用到猫这个对象身上,也就是动物的属性创建到了猫里面,
// 所以猫就继承了动物的方法
function animal(a, b) {
this.type = 'animal'
this.behavior = function(){
console.log(this.type+" is running")
}
}
function cat(a, b) {
this.name = 'wsscat'
//这里call的意思就是把animal的方法应用到cat这个对象身上
//所以cat就继承了animal的方法
animal.call(this);
}
console.log(new cat())
</script>
</html>
github地址:https://github.com/lianglixiong/javascript-note/tree/master

浙公网安备 33010602011771号