JavaScript language essence four

. Will often turn a complete thing into a myriad of images, like a convex mirror, the front view, a blur – William Shakespeare “Richard II”

Start:

  • Inheritance is an important topic in most programming languages
  • In class-based languages (e.gJAVA), inheritance provides two important services
    • Code reuse, significantly reduce software development costs
    • Class inheritance can reduce the workload by introducing a set of type system specifications
  • JavaScriptIs a weakly typed language that does not require conversions and does not require concern about object inheritance
  • JavaScriptProvides a richer set of code reuse patterns that mimic class-based patterns
  • JavaScriptIs a prototype-based language, meaning that objects inherit directly from other objects

pseudo-classes

  • Some of the complex syntax in javascript looks like those in class-based languages. Instead of directly making objects inherit from other objects, it uses constructor functions to generate objects

    • When a function object is created,FunctionThe function object generated by the constructor runs:
    this.prototype = { constructor: this };
    Copy the code
    • A new object is givenprototypeProperty, (the value is containsconstructorProperty with the value of the new function)
    • prototypeUsed to store inheritance characteristicsjavascriptEach function inprototypeattribute
    • When the constructor invocation pattern is adopted, (usingnew), the execution of the function changes
  • Define a constructor and extend its prototype

    var Man = function (name) {
      this.name = name;
    };
    Man.prototype.getName = function () {
      return this.name;
    };
    Man.prototype.says = function () {
      return this.saying || "";
    };
    Copy the code
  • Structure instance

    var myName=new Man('poo');
    var name=myName.getName();
    console.log(name);// poo
    Copy the code
  • You can also construct another pseudo-class that inherits from Man,

    var Dog=function(name){
      this.name=name;
      this.saying='aHa';
    }
    Dog.prototype=new Man();// Replace its prototype
    Dog.prototype.wangwang=function(n){
      var i,txt=' ';
      for(i=0; i<n; i++){ s=s? s+='~':'wang'
      }
      return txt;
    }
    var yourDog=new Dog('flower')
    var says=yourDog.says();// aHa
    var wangwang=yourDog.wangwang(3);/ / wang ~ ~
    Copy the code
  • A serious hazard of using constructors is that a constructor call that is not preceded by new does not bind this to the new object. Instead, it binds to the global, destroying the global environment

  • To reduce this risk, the constructor function is conventionally capitalized.

Object specifier

  • Usually the constructor takes some arguments, to avoid problems caused by misremembering the order
  • A simple object specifier is usually used to describe this
  • It doesn’t matter what order it is in, and it’s easier to read and use. Such as:
var myObj=maker(a,b,c,d);
// the above can be written as
var myObj=maker({
  isa:a,
  isb:b,
  isc:c,
  isd:d
})
Copy the code

The prototype

  • Prototype-based inheritance is conceptually simpler than class-based inheritance — that is, the new object can inherit the properties of the old object
  • For example, use object literals to construct an object
var man = {
  name: "poo".getName: function () {
    return this.name;
  },
  says: function () {
    return this.saying || ""; }};Copy the code
  • recyclingObject.createMethod to construct other instances
var myFriends = Object.create(man);
myFriends.name = "tomato";
myFriends.says = "Hi~ potato";
myFriends.getName = function () {
  return this.name + "" + this.says;
};
Copy the code
  • By customizing the new object to specify how it is different from the base object it is based on, this is called differentiation inheritance.

functional

  • The disadvantage of the inheritance pattern is that data privacy is not strong, because the properties in the object are visible
  • If you want to construct private properties, you can use the application module pattern
  • Construct a function from which objects can be generated (it does not need to use the new operator, so the name should not be capitulated)
    1. Create a new object. useObject.createmethods
    2. Defines private instance variables and methods that are passed in functionsvarStatement defines a common variable
    3. Extend the method to the current new object so that the method has access parameters and (2)varThe privileges of declared ordinary variables
    4. Returns the current new object.

Such as:

var constructor=function(spec,my) {var that,//- Other private instance variables
  my=my||{};
  // Add shared variables and functions to my
  that=// A new object
  // The privileged method added to that
  return that;
}
Copy the code

The Spec object contains all the information that the constructor needs to construct a new instance. The contents of a spec may be copied to private variables, or changed by other functions, or methods may have access to the spec as needed.

  • myObject is a privately shared container for constructors in the inheritance chain,myObject can be used optionally ifmyIf the value is empty, one is created myObject (my=my||{ }
  • Then declare the object’s private instance variables and methods. The constructor’s variables and inner functions become private members of the instance, and the inner functions are accessiblespec my thatAnd other variables.
  • And then through the assignment statement, we givemyExample Add a share private member
 my.member=value
Copy the code
  • Then we construct a new object and assign it tothat“, and then expand, the latter I am confused, do not understand.

parts

  • Objects can be assembled using a set of widgets, such as constructing a function that adds time to the object
  • Add to an objectonMethod,fireMethod and private event registry objects
var eventuality = function (that) {
  var registry = {};
  /** * Fires an event on an object * either a string containing the event name * or an object containing the type attribute of the event name * a function matching the event name in the event handler registered with the on method is called */
  that.fire = function (event) {
    var array,
      func,
      handler,
      type = typeof event === "string" ? event : event.type;
    // If there is a set of events in the event, iterate and execute sequentially
    if (registry.hasOwnProperty(type)) {
      array = registry[type];
      for (let i = 0; i < array.length; i++) {
        handler = array[i];
        Each handler contains a method and a set of optional parameters
        // If the method is a string, the function is found
        func = handler.method;
        if (typeof func === "string") {
          func = this[func];
        }
        // Call this handler, passing it if it includes arguments, passing the object otherwise
        func.apply(this, handler.parameters || [event]); }}return this;
  };
  // Register an event, construct a handler entry, and insert it into the handler array
  // If this type of event does not exist, construct
  that.on = function (type, method, parameters) {
    var handler = {
      method: method,
      parameters: parameters,
    };
    if (registry.hasOwnProperty(type)) {
      registry[type].push(handler);
    } else {
      registry[type] = [handler];
    }
    return this;
  };
  return that;
};
Copy the code
  • Can be called on any individual objecteventuality, which grants its event handling method, is also available inthatCall it in the constructor function before returning.
eventuality(that);
Copy the code
  • In the current mode:

    • A constructor function assembles an object from a set of parts
    • becauseJavaScriptBecause of a weakly typed language, there is no need to understand the inheritance of objects in the type system
    • If you want toeventualityAccess the private state of the object, the collection of private membersmyPassed in

You may also be interested in the following

  • # JavaScript Language Essentials 1 (simple lab)
  • Everything is an Object
  • # JavaScript Language Essentials 3 (Core — functions)
  • Arrays and array method sets
  • # JavaScript language Essence 6 (JS method set)
  • How are some of the apis implemented in # VUE3.0?
  • JavaScript reads local file configuration (compatible with lower IE versions)
  • # What do you ask about the front end of one year’s work experience?