why prototype is undefined

后端 未结 2 622
一个人的身影
一个人的身影 2021-02-02 17:04

I known this has been asked hundreds of times, however, I can\'t seem to grasp the concept of prototype

Here\'s my sample script

var config          


        
2条回答
  •  逝去的感伤
    2021-02-02 17:53

    I think you might be mixing concepts. Try grasping the concept of prototypes with classic prototype inheritance first, then you can get into all the new Object stuff.

    In JavaScript, every object (numbers, strings, objects, functions, arrays, regex, dates...) has a prototype which you can think of as a collection of methods (functions) that are common to all current and future instances of that object.

    To create a prototype chain you have to create a function and then call it with the new keyword to specify that it is a constructor. You can think of constructors as the main function that takes the parameters necessary to build new instances of your object.

    Having this in mind, you can extend native objects or create your own new prototype chains. This is similar to the concept of classes but much more powerful in practice.

    Similar to your example, you could write a prototype chain like this:

    // Very basic helper to extend prototypes of objects
    // I'm attaching this method to the Function prototype
    // so it'll be available for every function
    Function.prototype.inherits = function(parent) {
      this.prototype = Object.create(parent.prototype);
    }
    
    // Person constructor
    function Person(name, age, sex) {
      // Common to all Persons
      this.name = name;
      this.age = age;
      this.sex = sex;
    }
    
    Person.prototype = {
      // common to all Persons
      say: function(words) {
        return this.name +'says: '+ words;
      }
    };
    
    // Student constructor   
    function Student(name, age, sex, school) {
      // Set the variables on the parent object Person
      // using Student as a context.
      // This is similar to what other laguanges call 'super'
      Person.call(this, name, age, sex);
      this.school = school; // unique to Student
    }
    
    Student.inherits(Person); // inherit the prototype of Person
    
    var mike = new Student('Mike', 25, 'male', 'Downtown'); // create new student
    
    console.log(mike.say('hello world')); //=> "Mike says: hello world"
    

    In newer version of JavaScript (read EcmaScript) they added new ways to deal with objects and extend them. But the concept it's a bit different from classical prototype inheritance, it seems more complicated, and some more knowledge of how JS works underneath would help to really understand how it works, plus it doesn't work in older browsers. That's why I suggest you start with the classical pattern for which you'll find accurate and abundant information on the internet.

提交回复
热议问题