简体   繁体   English

原型:Apply vs call,new vs create

[英]Prototype: apply vs call, new vs create

I have a constructor function which I want to use as prototype for another constructor. 我有一个构造函数,想用作其他构造函数的原型。 both receive arguments: 两者都接收参数:

function Proto(arg) {}

function Sub(arg) {}

What's a better way to pass the argument from Sub constructor to Proto constructor: 将参数从Sub构造函数传递到Proto构造函数的更好方法是:

  • Proto.apply(this, arg);
  • Proto.call(this, arg); (pun unintended...) (双关语意料之外...)

    Second, when I want to actually set the prototype, what is the difference between: 其次,当我想实际设置原型时,它们之间有什么区别?

  • Sub.prototype = Object.create( Proto );
  • Sub.prototype = new Proto();

  • The difference between .call and .apply is that .call takes its arguments as separate arguments for the function, while .apply takes the arguments as a single array. 之间的差.call.apply的是, .call采取它的参数作为函数独立参数,而.apply取参数作为一个单一的阵列。 For example: 例如:

    function myFunction(x, y) {
        var z;
        // Do something
        return z;
    }
    
    var context = {};
    
    // The following function calls are equivalent:
    var fx = myFunction.call(context, 5, 'h');
    var fy = myFunction.apply(context, [5, 'h']);
    

    In cases where you don't know the length of the argument list at compile time, you have to use .apply . 如果您在编译时不知道参数列表的长度,则必须使用.apply But in this case you don't need to do that, and you can use the slightly simpler syntax of .call . 但是在这种情况下,您不需要这样做,可以使用.call稍微简单的语法。 If you were to do it with .apply , it would be Proto.apply(this, [arg]); 如果要使用.apply ,则应为Proto.apply(this, [arg]); .

    As for Object.create versus new : Again, you've got the expression wrong, it should be Sub.prototype = Object.create(Proto.prototype); 至于Object.createnew :再次,您有一个错误的表达式,它应该是Sub.prototype = Object.create(Proto.prototype); . I don't normally use Object.create , but as far as I can tell the only difference is the value of Sub.prototype.constructor . 我通常不使用Object.create ,但是据我所知,唯一的区别是Sub.prototype.constructor的值。 It probably doesn't matter much either way. 无论哪种方式都没关系。 However, the new way is more common and accepts arguments. 但是, new方法更常见并且接受参数。 (You can also give another argument to Object.create , but it works differently.) (您也可以给Object.create另一个参数,但是它的工作方式有所不同。)

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

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