문제

I read through several other articles on prototypal vs pseudoclassical instantiation and still have a few questions. I have included code below for illustration.

Questions are:

  1. Is Person effectively the same as Human?
  2. Are John and Alice essentially the same?
  3. What side effects can result from one way vs the other?
  4. Are there any significant performance issues I should be aware of?

    var Person = function() {
     hopes: function(){},
     dreams: function(){}
    };
    
    var John = Object.create(Person); // not supported in older browsers
    

    --

    var Human = function() {
    };
    
    Human.prototype.hopes = function(){}; // could add both hopes & dreams with an object
    Human.prototype.dreams = function(){};
    
    var Alice = new Human();
    
도움이 되었습니까?

해결책

Your syntax is a bit off in the first example, but yes, these will result in objects that are similar. In the first example, it should be:

var Person = {
 hopes: function(){},
 dreams: function(){}
};

There are some subtle differences though. Using the new keyword causes an object to be added to the prototype chain, e.g. Alice will now use Human's prototype chain. Object.create sets the object's prototype to the parameter, e.g. Person is John's prototype. These generally will be similar, except if you do Object.create(null), in which case you don't get the basic object prototype as if you did new Object();

You can run performance tests here http://jsperf.com/obj-create-vs-new/4

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top