简体   繁体   English

在javascript中调用另一个函数时值不变

[英]Value unchanged when another function is called in javascript

I was reading an article. 我正在读一篇文章。 It is related to javascript. 它与javascript有关。 Here, is a code sample from the article. 这是来自文章的代码示例。 Please look at below. 请看下面。

 function customobject(){ this.value = 2; } customobject.prototype.inc = function(){ this.value++; } function changer(func){ func(); } var o = new customobject(); alert(o.value); o.inc(); alert(o.value); changer(o.inc); alert(o.value); 

My question is Why is the value for "o.value" unchanged when changer(o.inc) is called ? 我的问题是,当调用更换器(o.inc)时,为什么“o.value”的值不变?

o.inc is just a reference to the anonymous function: o.inc只是对匿名函数的引用:

function() { 
    this.value++;
}

Whereas this is the scope in which the function is executed. this是执行函数的范围。 So when you run changer(o.inc) , this is actually pointing to the global, in browsers it's window . 所以当你运行changer(o.inc)this实际上是指向浏览器window的全局。 It doesn't necessarily have anything to do with o . 它不一定与o有任何关系。

You could bind the scope like this: 您可以像这样绑定范围:

function changer(func, scope){ 
    func.call(scope); // or apply
} 

changer(o.inc, o); 

Or simply: 或者干脆:

function changer(func){ 
    func();
}
changer(o.inc.bind(o));

The problem is because Function does not save instance for objects. 问题是因为Function不保存对象的实例。 You have to pass the object as argument so call your function, like this. 你必须将对象作为参数传递,所以调用你的函数,就像这样。

 function customobject(){ this.value = 2; } customobject.prototype.inc = function(){ this.value++; } function changer(o){ o.inc(); } var o = new customobject(); console.log(o.value); //It has to print 2 o.inc(); //Increment to 3 console.log(o.value); //It has to print 3 changer(o); //Increment to 4 console.log(o.value); //It has to print 4 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM