Javascript explain the use of 'this'

Javascript explain the use of 'this'

本文关键字:this of explain the use Javascript      更新时间:2023-09-26

我正在学习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是一个接受两个参数vanillacinnamon的函数。当调用时,它将创建一个至少有一个属性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));

没有thisnew的相同功能:

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不是任何事物的成员,因此thiswindow

要理解this,只需检查谁拥有该函数,若并没有任何所有者,则表示窗口。每个没有所有者的函数都自动归窗口所有。

另外,您可以更改临时所有者呼叫。

var b = function () {};
var c = { d: 1 };
b.call(c);

调用函数暂时将所有者更改为cthis将为c

正在创建新实例。

function E() { this.h = 2; }
E.prototype = { f: 1 };
E.prototype.g = function () { return this; };
var e = new E();
e.g();

在这种情况下,thiseprototype是一种结构,它可以让您描述新对象最初的样子。这里是{ h: 2, g: func, f: 1 }