0

我正在学习 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"];
}
4

3 回答 3

0

VanillaBean是一个接受两个参数的函数,称为vanillacinnamonvanilla当像下面这样调用时,它将创建一个具有至少一个属性的对象:

var flavour = new VanillaBean("cheap", 250);

flavour.vanilla然后将[1, "bean", "cheap"]

(感谢@FelixKling 和@t.niese。)

this指的是它创建的对象,而不是其他vanilla任何东西的其他属性。

如果您要使用涉及SomeVariable您的第一个版本,您仍然会得到一个列表,但它只是一个独立变量,而不是任何对象的属性(嗯window,可能,但是......)

于 2013-09-05T09:00:52.820 回答
0
var a = {};

this在对象:

a.test = function () { return this; };

在这种情况下this将是a因为function是 a 的成员。

a.t = function () {
  var b = function () { return this; };
  b();
};  

在这种情况下b,不是任何事物的成员,所以thiswindow

要了解this只需检查谁拥有功能,如果它没有任何所有者,它代表窗口。每个没有所有者的函数都自动归窗口所有。

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

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

调用函数暂时将所有者更改为c并将。thisc

创建新实例。

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 }

于 2013-09-05T09:08:20.677 回答
0

在 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没有and的相同功能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));
于 2013-09-05T09:10:53.093 回答