传递应用参数类数组对象返回错误的值

时间:2014-08-30 21:13:15

标签: javascript

文档说明:

  

apply()方法调用一个给定此值的函数   作为数组(或类数组对象)提供的参数。

     

thisArg

     

为乐趣召唤提供的价值。

     

argsArray

     

一个类似数组的对象,指定应该调用fun的参数,如果不应该为函数提供参数,则为null或undefined。

好的,这是我的测试:

function A(age){
  this.age=age;
}
A.prototype.random_age = Math.random();
function B(name,age){
  A.apply(this, arguments);
  this.name=name
}
B.prototype = new A();

var b = new B("John",25); 
console.log("age: " + b.age + " name: " + b.name + " random age " + b.random_age);

出乎意料的是,我得到以下内容:

age: John name: John random age 0.9844443484632327

年龄应该是25岁而不是#34; John"。我传递了这个(这是由A函数创建的对象)。我想把B&#39的属性复制到这里。并且这些属性中的值在参数array-like object中定义。我做错了什么?

2 个答案:

答案 0 :(得分:0)

A(age)

有一个参数。 arguments是一个包含两个元素的对象。当您只传递arguments对象时,您基本上会传递索引为0的元素,在您的情况下,该元素是名称。如果您反转参数,您将拥有所需的

function A(age){
  this.age=age;
}
A.prototype.random_age = Math.random();
function B(age, name){
  A.apply(this, arguments);
  this.name=name;
  console.log(arguments)
}
B.prototype = new A();

var b = new B(25, "John"); 
console.log("age: " + b.age + " name: " + b.name + " random age " + b.random_age);

但你真正应该做的是以适合你需要的方式操纵数据。

function A(age){
  this.age=age;
}
A.prototype.random_age = Math.random();
function B(name, age){
  A.apply(this, [arguments[1]]); // or even better A.apply(this, [age]);
  this.name=name;
  console.log(arguments)
}
B.prototype = new A();

var b = new B("John", 25); 
console.log("age: " + b.age + " name: " + b.name + " random age " + b.random_age);

答案 1 :(得分:0)

通过从B函数执行 A.apply(this,arguments),然后使用B接收到的两个参数调用A.因此,您必须忽略第一个参数(名称)。为此你可以这样做:

function A(age){
  this.age=age;
}
A.prototype.random_age = Math.random();

function B(name,age){
  this.name=name
  Array.prototype.shift.call(arguments); //Here we are deleting the first paramater of B
  A.apply(this, arguments);
}
B.prototype = new A();

var b = new B("John",25); 
console.log("age: " + b.age + " name: " + b.name + " random age " + b.random_age);