[英]Why can't I add a property to an object without using prototype, call or apply?
Take the following code snippet: 采取以下代码段:
Foo() {}
var bar = new Foo(); /* uses Foo as constructor for new object */
Now I create a function that will add the property x to my object and assign its value to 2; 现在,我创建一个将属性x添加到我的对象并将其值分配为2的函数;
function addX() {
this.x = 2;
}
My question is, why DOESN'T this succeed in adding the x property to the bar object: 我的问题是,为什么不能成功将x属性添加到bar对象:
addX(bar);
while this does: 虽然这样做:
addX.apply(bar);
Shouldn't they do the same thing? 他们不应该做同样的事情吗?
I'm a junior javascript programmer trying to get a better understanding of the language and OOP in general. 我是一名初级javascript程序员,试图全面了解该语言和OOP。 There's no corresponding real-world example, ie I'm not currently in the middle of a project.
没有相应的实际示例,即我目前不在项目中间。 I've just been learning what I can and cannot do with objects and I'm trying to figure out why.
我一直在学习我可以和不能使用对象做什么,并且我试图找出原因。
A function if "applied" to an object, would mean that the function will get "this" variable which would be the object itself. 如果将函数“应用于”对象,则意味着该函数将获得“ this”变量,该变量将是对象本身。 Whereas just calling addX(bar) passes bar as a parameter to the function.
而仅调用addX(bar)会将bar作为参数传递给函数。
So had addX been written like this: 因此,addX是这样写的:
function addX(barObject) {
barObject.x = 2;
}
The call addX(bar) would have worked. 调用addX(bar)就可以了。
Whereas,in your example addX.apply(bar), internally does this: 而在您的示例addX.apply(bar)内部执行此操作:
// apply does the following internally
bar.addX = function()
{
this.x = 2;
}
bar.addX()
// end of scope for apply
hence addX(bar) does not do anything in your example, because in that case, "this" does not belong to anything but the function itself. 因此addX(bar)在您的示例中不执行任何操作,因为在这种情况下,“ this”不属于任何函数,而是函数本身。
Modify your addX method as follows. 如下修改您的addX方法。 Calling your previous method does not pass the context as parameter.
调用先前的方法不会将上下文作为参数传递。
function addX(barx) {
barx.x = 2;
}
Every function has a special 'this' object. 每个函数都有一个特殊的“ this”对象。 When a function is called, the this value is set, which is a reference to the context object the function is operating on (when a function is called in global scope of a web page, this this object points to window object).
调用函数时,将设置此值,该值是对该函数所操作的上下文对象的引用(在网页的全局范围内调用函数时,此对象指向窗口对象)。 apply() method of a function is used to call the function with a particular this value.
函数的apply()方法用于调用具有特定this值的函数。 Calling the function with apply method supplied with the 'bar' argument sets the this value of the function to the bar object.
使用“ bar”参数提供的apply方法调用函数会将函数的this值设置为bar对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.