将值传递给另一个原型函数
Passing value to another prototype function
进入Javascript原型,我不知道为什么当我从另一个原型调用一个原型函数并将值传递给另一个时,值不会更新。
这是与关闭有关的问题吗?我尝试使用全局变量,但仍然不起作用。有什么帮助吗?
function test(elem){
this.opt =
this.elem = $(elem)
this.method1();
}
test.prototype.method1 = function() {
var output = 1;
this.method2(output);
console.log(output);
}
test.prototype.method2 = function(output) {
output += 1;
}
var data = new test(this);
当我在method1函数中调用method2时,输出不会得到更新,因此它仍然会控制台1。
您的问题基本上是参考与值
Javascript总是通过值传递,但当变量引用对象(包括数组);值";是对对象的引用。
更改变量的值永远不会更改基础基元或对象,它只是将变量指向一个新的基元或对象
但是,更改由变量确实会更改基础对象。
你有三种可能性:
- 将变量包裹在对象中:http://jsfiddle.net/8c2p349g/
function test(elem, opt){
this.opt = opt;
this.elem = $(elem);
this.method1();
}
test.prototype.method1 = function() {
var data = {
output: 1
};
this.method2(data);
console.log(data.output);
}
test.prototype.method2 = function(data) {
data.output += 1;
}
var inst = new test();
- 从
method2
返回output
:http://jsfiddle.net/8c2p349g/1/
function test(elem, opt){
this.opt = opt;
this.elem = $(elem);
this.method1();
}
test.prototype.method1 = function() {
var output = 1;
output = this.method2(output);
console.log(output);
}
test.prototype.method2 = function(output) {
return output + 1;
}
var inst = new test();
- 将
output
附加为test
的属性:http://jsfiddle.net/8c2p349g/2/
function test(elem, opt){
this.opt = opt;
this.elem = $(elem);
this.method1();
}
test.prototype.method1 = function() {
this.output = 1;
this.method2(this.output);
console.log(this.output);
}
test.prototype.method2 = function(output) {
this.output += 1;
}
var inst = new test();
在method2
中,output
是该函数作用域上的一个变量
它没有指向method1
中的output
。
您必须从method2
:返回新值
test.prototype.method1 = function() {
var output = 1;
output = this.method2(output);
console.log(output);
}
test.prototype.method2 = function(output) {
return output + 1;
}
output
是method1
的局部变量,它不存在于method2
的范围内。
相关文章:
- 使用方括号访问插件原型函数
- 使用setInterval调用原型函数时出现问题
- 无法从angularjs调用JavaScript原型函数
- AngularJS ng repeat显示原型函数未定义
- 在 Redux 状态下存储具有原型函数的对象
- Javascript 中的构造函数不会返回由原型函数传递的正确值
- JavaScript:在哪里放置原型函数
- 创建所有原型函数均可访问的局部变量
- 可以'这'在原型函数中未定义
- 使用特权Getter/Setter函数的JavaScript原型函数
- Javascript、node、Q promise、原型函数和“;这个“;
- 在Javascript中将对象原型函数绑定到对象
- 从node.js模块中向JSON添加原型函数
- 从另一个(包括其自身)触发一个原型函数
- Javascript原型继承原型函数调用
- JavaScript–从另一个原型函数调用原型的一个函数
- 访问原型函数中的私有成员
- 如何在AngularJS中将依赖关系传递给原型函数
- 这两种用 JavaScript 编写原型函数的方式有什么区别?
- 为什么不能使用lambda来定义原型函数