![](/img/trans.png)
[英]Why declaring an anonymous JavaScript function as a function parameter?
[英]Why is 'this' used in javascript while declaring a function to reference an inherited parameter?
我是一位JavaScript新手,我不明白为什么将'this'用作参数以及调用原型的实际参数...在提供的图像中,您可以看到其用法示例。 那么,为什么有必要添加“ this”作为参数? 它到底是做什么的?
'use strict';
function Animal(voice){
this.voice = voice || 'grunt'
}
Animal.prototype.speak = function(){
display(this.voice)
}
function Cat(name, color){
Animal.call(this, 'Meow')
this.name = name
this.color = color
}
Cat.prototype = Object.create(Animal.prototype)
var Fluffy = new Cat('Fluffy', 'White')
Fluffy.speak()
这个
Animal.call(this, 'Meow');
......被使用,以便调用中Animal
, this
将把它指的是在同一件事Cat
,让Animal
在同一实例设置其实例属性。 如果您只是做了Animal('Meow')
,则当Animal
写入this.voice
,它将抛出一个错误(在严格模式下)或添加一个称为voice
的全局变量(在宽松模式下),但这都不是理想的结果。
更多:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.