将值传递给另一个原型函数

Passing value to another prototype function

本文关键字:原型 函数 另一个 值传      更新时间:2023-09-26

进入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总是通过值传递,但当变量引用对象(包括数组);值";是对对象的引用。

更改变量的值永远不会更改基础基元或对象,它只是将变量指向一个新的基元或对象

但是,更改由变量确实会更改基础对象。

你有三种可能性:

  1. 将变量包裹在对象中: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();

  1. 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();

  1. 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;
}

outputmethod1的局部变量,它不存在于method2的范围内。