从sololearn
function mathCalc (height, weight) {
this.height = height;
this.weight = weight;
// this.sampleCalc = ; (taken out)
}
为什么需要这样做:
this.height = height;
this.weight = weight;
其背后的原因是什么?
答案 0 :(得分:1)
简而言之,this
是函数的所有者对象。如果您有两个调用函数的对象或元素-如何将适当的值放在调用该函数的适当元素中?使用this
可以消除重复代码等的需要。
从技术上讲,您没有使用它;但它有其用途。
您可以read more here或here。
这里有一个点击测试代码段,在这里我可以使用一个功能来提醒this
点击的div ID,而不必为每个div编写一个功能。
var div = document.getElementsByTagName('div');
var i;
for (i = 0; i < div.length; ++i) {
div[i].onclick = function() {
alert(this.id);
}
}
<div id="test1">Click Test 1</div>
<div id="test2">Click Test 2</div>
<div id="test3">Click Test 3</div>
请记住,这在jQuery中更容易-但我不认为此示例需要包括CDN。但是,看起来像这样;
$('div').on('click', function() {
alert(this.id);
})
答案 1 :(得分:1)
height
和weight
只是传递给函数的参数的参数。如果您正在学习,使用不同的名称可能会有所帮助。
this
是指函数本身。当作为对象/类时,它将保留这些值。请注意,在下面的对象输出中,未保留h
和w
,而height
和weight
被保留。还要注意,one
和two
具有不同的值,它们是在初始化时传递给函数的值。
function mathCalc (h, w) {
this.height = h
this.weight = w
}
let one = new mathCalc(1,3)
let two = new mathCalc(2,4)
console.log('one:',one)
console.log('two:',two)
答案 2 :(得分:1)
对于仅被调用一次的函数,避免使用{{ form.<field_name>.errors }}
是完全有意义的。但是,对于持久状态,this
可能会有用。请注意,只有在使用this
关键字时,this
才会反弹。
new
使用ES6 Javascript,有一种更干净的方法可以利用此功能。
function Worm() {
this.size = 1;
this.grow = function() {
++this.size;
}
}
const wormy = new Worm();
console.log(wormy.size);
wormy.grow();
console.log(wormy.size);
答案 3 :(得分:1)
this
是函数调用者的关键字,用于函数表达式和函数声明。对于构造函数(下面将说明)和对象方法,this
引用对象本身。以下是上述类型的示例:
function myFunc() { return this; } //function declaration
const myVar = function() { return this; } //function expression
const obj = {a: 1, whatIsA: function() { return this.a } } //whatIsA is an object method
如果从全局上下文(而不是在另一个函数内部)调用以上任一函数,则this
是Window对象。浏览器默认将this
设置为窗口(当您考虑时,窗口是自浏览器运行文件以来的函数调用者)。
myFunc(); //outputs "Window" obj
myVar(); //also outputs "Window" obj
对于用new
实例化的构造函数,this
绑定到新创建的对象。
我认为证明this
如此有用的最好方法是举一个例子。检查以下代码:
function Dog(name) {
this.name = name;
this.bones = 0;
this.addBone = function(numOfBones) {
this.bones += numOfBones;
return this;
}
}
const clifford = new Dog('Clifford');
我们有一个称为Dog的构造函数(意味着我们将通过此函数创建新对象)。
考虑当我们创建一个名为“ Clifford”的new Dog
时会发生什么。 new
关键字在内存中为Clifford创建了一个全新的对象,该对象是Dog构造函数的一个实例。因此,由于我们创建了以前不存在的内容,因此this
引用了对象本身。如果我们将this.name = name
替换为let myName = name
,会发生什么?我们将无法访问myName,因为myName不属于Dog对象的品牌new
实例的一部分。
让我们给克利福德一些骨头。
clifford.addBone(1).addBone(2).addBone(3);
console.log(clifford.bones); //outputs 6
我们怎么可能像上面那样链接方法?因为该方法返回this
!
因此,在向Clifford的骨骼添加骨骼之后,我们将返回对象。这使我们再次返回了对象本身。
箭头功能的行为略有不同。 this
is inherited from the current lexical scope and not the caller.
答案 4 :(得分:-3)
这是一种写对象名称的简便方法,对具有许多对象的大型程序很有用。