0

我想知道是否可以从原型对象返回多个值。我需要返回几个数组的值并在稍后调用它们。下面是我的代码示例。如果需要,我可以显示一个 JSFiddle。谢谢!

 EmployeeObj.prototype.showEmployee = function(emPhoto0,emPhoto01){
     var employeePhoto = new Array();
     employeePhoto[emPhoto0] = new Image();
     employeePhoto[emPhoto0].src = "pics/taylor.jpg";
     employeePhoto[emPhoto01] = new Image();
     employeePhoto[emPhoto01].src = "pics/roger.jpg";

     var showPhoto1 = employeePhoto[emPhoto0];
     var showPhoto2 = employeePhoto[emPhoto1];

     return showPhoto1;
     return showPhoto2;
 };
4

4 回答 4

1

您不能return以这种方式使用多个语句 - 只有第一个评估会发生,但您可以返回ObjectArray,并从中访问您想要的内容。

EmployeeObj.prototype.showEmployee = function (emPhoto0, emPhoto01) {
    var employeePhoto = new Array();
    employeePhoto[emPhoto0] = new Image();
    employeePhoto[emPhoto0].src = "pics/taylor.jpg";
    employeePhoto[emPhoto01] = new Image();
    employeePhoto[emPhoto01].src = "pics/roger.jpg";
    var showPhoto1 = employeePhoto[emPhoto0];
    var showPhoto2 = employeePhoto[emPhoto1];
    return {'showPhoto1': showPhoto1, 'showPhoto2': showPhoto2};
    // or [showPhoto1, showPhoto2];
};

然后,您将通过

var em = new EmployeeObj(/* ... */),
    photos = em.showEmployee(/* ... */);
photos['showPhoto1']; // or photos['showPhoto2']
// or photos[0], photos[1], if you used the Array version
于 2013-06-04T11:41:49.483 回答
1

您可以将 2 个结果组合成一个对象:

return { photo1: showPhoto1, photo2: showPhoto2 };
于 2013-06-04T11:42:39.340 回答
0

不,您不能return在一个函数中执行多个语句。但是您可以返回一个包含结果的数组。在您的情况下,这很简单:

return employeePhoto;
于 2013-06-04T11:45:22.930 回答
0

这个问题的现代答案是通过返回一个数组来使用解构,并将数组解构为调用方的变量:

EmployeeObj.prototype.showEmployee = function (emPhoto0, emPhoto01) {
    ...
    return [showPhoto1,showPhoto2]
}

// Calling showEmployee
[showPh1, showPh2] = <Employee>.showEmployee(emPh0, emPh01)

对这种模式的支持现在在浏览器中慢慢出现,node.js 应该很快就会支持。

这种模式最酷的地方在于,它允许我们实现一种替代错误处理模式,该模式与Go 语言通过返回值和错误进行错误处理相匹配。

于 2016-02-26T14:53:17.503 回答