Javascript explain the use of 'this'
Javascript explain the use of 'this'
我正在学习javascript,并试图理解javascript为什么使用this.vanilla
。
这和写一样吗
var SomeVariable = [1, "bean", vanilla ? vanilla : "Madagascar Bourbon"];
使用和参数vanilla
相同的名称似乎非常令人困惑。
var VanillaBean = function(vanilla, cinnamon) {
this.vanilla = [1, "bean", vanilla ? vanilla : "Madagascar Bourbon"];
}
这里VanillaBean
是一个接受两个参数vanilla
和cinnamon
的函数。当调用时,它将创建一个至少有一个属性vanilla
的对象,如下所示:
var flavour = new VanillaBean("cheap", 250);
则CCD_ 7将是CCD_。
(感谢@FelixKling和@t.niese。)
this
指的是它创建的对象,而不是其他任何东西的vanilla
属性。
如果您使用涉及SomeVariable
的第一个版本,您仍然会得到一个列表,但它只是一个独立的变量,而不是任何对象的属性(好吧,可能是window
,但…)
在html元素中使用时,this
指的是DOM中的元素。
示例:
<script type="text/javascript">
function hover(domElement) {
domElement.style.backgroundColor = '#CCC';
}
</script>
<div onmouseover="hover(this);">Hover me</div>
当在非返回函数中使用this
时,该函数将成为对象构造函数,而this
指的是隐式创建的对象,当使用new
调用该函数时,该对象将自动返回。
示例:
function Point(x, y) {
this.x = x || 0;
this.y = y || 0;
this.distance = function (point) {
return Math.sqrt(
Math.pow(point.x - this.x, 2) +
Math.pow(point.y - this.y, 2)
);
};
}
var a = new Point(10, 10);
var b = new Point(100, 100);
document.write(a.distance(b));
没有this
和new
的相同功能:
function Point(x, y) {
obj = {};
obj.x = x || 0;
obj.y = y || 0;
obj.distance = function (point) {
return Math.sqrt(
Math.pow(point.x - this.x, 2) +
Math.pow(point.y - this.y, 2)
);
};
return obj;
}
var a = Point(10, 10);
var b = Point(100, 100);
document.write(a.distance(b));
var a = {};
对象中的this
:
a.test = function () { return this; };
在这种情况下,this
将是a
,因为function
是的成员
a.t = function () {
var b = function () { return this; };
b();
};
在这种情况下,b
不是任何事物的成员,因此this
是window
。
要理解this
,只需检查谁拥有该函数,若并没有任何所有者,则表示窗口。每个没有所有者的函数都自动归窗口所有。
另外,您可以更改临时所有者呼叫。
var b = function () {};
var c = { d: 1 };
b.call(c);
调用函数暂时将所有者更改为c
,this
将为c
。
正在创建新实例。
function E() { this.h = 2; }
E.prototype = { f: 1 };
E.prototype.g = function () { return this; };
var e = new E();
e.g();
在这种情况下,this
是e
。prototype
是一种结构,它可以让您描述新对象最初的样子。这里是{ h: 2, g: func, f: 1 }
。
相关文章:
- $(this).prop('property') vs. this.property
- Twitter Bootstrap typeahead:使用“this”获取上下文/调用元素
- 在另一个函数中使用变量this
- this.router在AngularJS 2中未定义
- reactjs this.refs vs document.getElementById
- HighChart : Usage of setData
- JavaScript 中的嵌套函数和 “this” 关键字
- React+Meteor:this.ops返回未定义
- javascript中对象构造函数中的var属性与this.properties
- 函数中this和var之间的区别
- Advantage of (function() {/*...*/}).call(this);
- Javascript explain the use of 'this'
- scope of this.submit()?
- inner text of element passed as <span onclick=foo(this) &
- Can't get ID of 'this' variable
- Impact of calling this.$scope.$digest();
- JQuery - What is the purpose of this syntax $(function () {
- what will be the value of 'this'?
- Jquery onclick this remove both of span
- jQuery: $(this).attr('id') not find id of element -