Pseudo-classical vs. “The JavaScript way”

后端 未结 4 706
野趣味
野趣味 2021-01-30 03:22

Just finished reading Crockford\'s \"JavaScript: The Good Parts\" and I have a question concerning his stance on the psuedo-classical vs. prototypal approaches.

4条回答
  •  隐瞒了意图╮
    2021-01-30 03:58

    Your implementation is problematic because you're replacing the entire prototype object, losing the properties of the inherited function prototype and it would also break, or at least make it more difficult, the ability to make use of inheritance later on if you wrote other classes the same way.

    A method more suited to Javascript would be:

    var MyClass = function (storeThis) {
     this.storage = storeThis
    }
    
    MyClass.prototype.getStorage = function (){
       return this.storage;
    }
    
    MyClass.prototype.setStorage = function (newStorage){
      this.storage = newStorage;
    }
    

    Use it:

    var myInstance = new MyClass("sup");
    alert("myInstance storage: " + myInstance.getStorage());
    myInstance.setStroage("something else");
    

    As for the 'new' keyword and Crawford's problems with it, I can't really answer, because I haven't read the book, but I can see how you could create a new object by calling any function with the new keyword, including functions that are supposed to be methods of a class.

    And when someone says something, such as a design pattern, is more 'expressive', he or she generally means that the design pattern is clear and simple to understand as to what it is achieving and how.

提交回复
热议问题