Summary of objects and functions in JS

Object data type value

{} Ordinary objects

[] array

/ ^ $/ regular

Math function

Instances are object data types (except values created by primitive type literals)

The prototype property of the function

Instance’s __proto__ attribute (pointing to the prototype of the instance’s class)

Functions are also of object data type

Function data type value

Common function

All classes (including built-in and custom classes)

typeof Object    // "function" Object is the built-in class
typeof String    // "function" String is the built-in class

function Fn(){}
typeof Fn    / / Fn is kind of "function"
Copy the code

Object data type

  • 1. All of themFunction (class)‘prototype’ comes with one attribute: prototype

This property value is the value of the object’s data type. In the current Prototype object, it stores the public properties and methods that the class needs to use for instances.

  • Prototype is object data. By default, the browser creates a heap for itInherently comes with a property: constructor, this property stores the current valueThe function itself
  • 3,Every object(contains instances of each class, function(because function is also object type data))It comes with a built-in attribute: __proto__, the property value isPrototype of the current instance classIf you cannot determine whose instance it is, it is an instance of Object

Prototype is a Function with no prototype

Function datatype __proto__ points to function.prototype

The instance’s __proto__ is the prototype of its owning class; Prototype = constructor

Stereotype effect: The public property methods used by the instance are on the stereotype of the class

All objects are instances of the Object class

An object is an instance of all classes on its prototype chain (not just the parent, but also the grandparent)

  • (1) The __proto__ attribute on the prototype of the Object datatype is null, i.eObject.prototype.__proto__=nullIf it is to be pointed at, it is to himself
  • But (2)Object.__proto__Prototype (The built-in classes are all functions, and the Function’s __proto__ refers to the built-in class function.prototype)

Prototype C. Stereotypes are of object data type

_proto_ : Prototype chain

When using a method or property of an instance, if the private property is not found in the public property, go to the public property

// Use a combination of 'constructor pattern' and 'prototype pattern'
function Fn(name,age){
    this.name=name;
    this.age=age;
    this.say=function(){
        console.log('my name is'+this.name+'! I am'+this.age+'years old')}; } Fn.prototype.say=function(){
    console.log('hello world')
}
Fn.prototype.eat=function(){
    console.log('i like food')}var f1=new Fn('aaa'.18);
var f2=new Fn('bbb'.28);

  var f=new Fn;
console.log(f.say)  // Display private attributes; If it's not in the private property look in the public property

f1.say===f2.say   // False is private and belongs to both instances
f1.eat===f2.eat   //true is public
f1.__proto__.say===f2.say   //false f1.__proto__ skip private to find public private
f2.eat===Fn.prototype.eat   //true is public

f1.constructor    Constructor (Fn. Prototype. constructor); //Fn. Prototype. constructor (Fn. Prototype. constructor); //Fn
Fn.prototype.constructor    //Fn
Fn.prototype.constructor===Fn    //trueProcess analysis:// Variable promotion: open up a Fn heap memory space to store code stringsFn. Prototype This object will be stored in a heap by default:constructorisFnEvery object itself comes with an inherent property: \__proto__, the property value is the prototype of the class to which the current object belongs (prototype)this.name=name; this.age=age; this.say=functionAre given to the principal executor (this) set private propertiesFn.prototype.sayAn attribute was added manuallysay(sayisfunction) Public attributesFn.prototype.eatAn attribute was added manuallyeat(eatisfunction) Public attributesvar f1=new Fn('aaa'.18);
    f1isFnClass (object data type)thisPointing to the instancef1
    f1.name:aaa    f1.age: 19f1.say:function  (They're all private properties)
    f1.__proto__Each instance comes with an inherent property:__proto__, the property value is the prototype of the class to which the current object belongs (prototype) :Fn.prototype

var f2=new Fn('bbb'.28);
    f2isFnClass (object data type)thisPointing to the instancef2
    f2.name:bbb    f2.age28:f2.say:function  (They're all private properties)
    f2.__proto__Each instance comes with an inherent property:__proto__, the property value is the prototype of the class to which the current object belongs (prototype) :Fn.prototype

f1It's an object data type as wellObjectAn instance of theCopy the code

Constructor, prototype, and instance relationships

Each constructor has a prototype object, which contains a pointer to the constructor, and each instance contains an internal pointer to the prototype object (__proto__).

Prototype chain: a mechanism based on __proto__ lookups up.

When we operate on a property or method of an instance, we first look to see if we have a private property or method,

1, found, end the search, use their own private can

__proto__(prototype.__proto__) : prototype.__proto__ (prototype.__proto__) : prototype.__proto__ (prototype.__proto__); The property or method of the operation does not exist

Object. Prototype is eventually found in __proto__ for any data

The default prototype of all functions is an instance of Object, so the default prototype will contain an internal pointer (__proto__) to Object.prototype, which is the fundamental reason all custom classes integrate toString, valueOf

If a Function (regardless of class or subclass) is an instance of the built-in Function class, the __proto__ of any Function refers to function. prototype, including Function itself. The Function. __proto__ = = = Function. The prototype to true

Any value can use the methods provided on Object.prototype

You can use call, apply, bind as long as it’s a function

Function. Prototype is an anonymous Function, but it doesn’t have prototype. Prototype (function.prototype. __proto__ === object.prototype)

  • Object.hasownproperty: passes its property__proto__To find the Object. The prototype. HasOwnProperty,
  • Because Object is a class.Object.__proto__findFunction.prototypeAnd then through theFunction.prototype.__proto__Find hasOwnProperty on Object.prototype
function Fn(){
	this.n=100;
}
Fn.prototype.getN=function(){
	console.log(this.n)
}
Fn.AA=200;
var f=new Fn();
Copy the code

Object is the base class of the Object datatype. The __proto__ attribute on its prototype is null, that is, object.prototype. __proto__=null. Prototype (classes are all functions, and the Function’s __proto__ refers to the built-in class function.prototype)

The object’s __proto__ refers to the prototype of its owning class; Function __proto__ points to the prototype of the built-in Function class

var f=new Fn(); F is an instance of Fn and the object returned by new Fn(), not function; So its __proto__ doesn’t point to function.prototype

Some of the underlying issues raised by the chain of built-in class archetypes

Arr.push (): Ary ** finds the push method on the Array prototype through the look-up mechanism of the prototype chain, and then makes the push method append to the end of the Array

So arr._proto_.push() can also find push methods (because arr.__proto_ is the prototype for Array), but this in push changes to arr._proto; Is added to arr._proto_ (array.prototype)

Array.prototype.push() can also be found by adding the push method to array.prototype

An instance or an object can operate on properties and methods because they are found on its prototype chain and cannot operate if they are not

The method is first found through the look-up mechanism of the prototype chain, and then the method is executed

The difference between an array and a class array:

Array __proto__ refers to Array, so you can use Array methods (push, etc.)

Class Array __proto__ refers to Object, so can’t use Array methods (push, etc.)

Array is a class of Array. Classes that use arrays directly from Object cannot use Array methods

Private and public properties are relativistic, and we need to look at which objects are relative:

1. Push is common to instances

2. Push is private to array. prototype

All attributes found by __proto__ are public, and vice versa

var arr=[];
arr.hasOwnProperty('push')     false
'push' in arr                  true
Array.prototype.hasOwnProperty('push')   true
Copy the code

Arguments.__proto__ = array. prototype So arguments can use Array methods (IE prevents __proto__ from changing)

This in the prototype chain

The this pointing problem with private or public methods provided in the stereotype chain:

  • 1. Look who’s in front of you. This is who
  • 2. Replace this in the method you want to execute
  • 3. After the replacement, if you want to know the result, you just need to search according to the search mechanism of the prototype chain
function Fn(name,age){
    this.name=name;
    this.age=age;
    this.say=function(){
	    console.log(this)
        console.log('my name is'+this.name+'! I am'+this.age+'years old')}; } Fn.prototype.say=function(){
	console.log(this)
    console.log('hello world')
}
Fn.prototype.eat=function(){
	console.log(this)
    console.log('i like food')}var f1=new Fn('aaa'.18);
var f2=new Fn('bbb'.28);

f1.say()                //this:f1 looks for private attributes and methods
f1.__proto__.say()      //this:f1.__proto__ looks for common attributes and methods (Fn. Prototype's) 'hello world'

Fn.prototype.say()      //this:Fn. Prototype = 'hello world'
Copy the code

Batch extend properties and methods on prototypes

1. Set the alias method

To ensure that constructor points to the original constructor, the constructor attribute must be added to the custom object.

There is a problem: the constructor attribute does not exist in the heap, so the constructor instance finds Object, which is not good. We should reset constructor to ensure the integrity of the mechanism.

After the prototype pointing is redone, the properties and methods stored in the default heap memory of the browser are useless. Only those stored in the new memory are useful, so use them carefully when the original prototype chain has something. And the built-in classes don’t allow it (refactoring prototypes)

function Fn(name,age){
    this.name=name;
    this.age=age;
}

// Add 1 method
Fn.prototype.aa=function(){}// Batch increment

// set the alias method
var pro=Fn.prototype; // point to the same heap memory
pro.aa=function(){}

//2
Fn.prototype={
    // Reset constructor to ensure the integrity of the mechanism
     constructor:Fn,
     aa:function(){},
     bb:function(){}}var f=new Fn('aaa'.18);
Copy the code
/ / the jQuery source code
~function(){
    var jQuery =function(selector,context){
        return new jQuery.fn.init(selector,context);
    }
    jQuery.fn=jQuery.prototype={
        constructor:jQuery,
        init:function(selector,context){}};window$=window.jQuery=jQuery; } ()Copy the code

Extension method based on built-in class prototype

1. We’d better set a prefix for our new method: to prevent our new method from colliding with the built-in method, replace the built-in method

2. In the extended method this is the data being processed and cannot be passed (arr.myDISTINCT ())

Arr. Push () returns the length of the array after the push, which is a number

The differences between extended prototype approaches

__proto__ can find Fn. Prototype; Constructor is Fn

__proto__ can’t find Fn. Prototype; Constructor is Object

/ / 1
function Fn(name,age){
    this.name=name;
    this.age=age;
}

Fn.prototype.say=function(){
    console.log(this)
    console.log('hello world')}var f1=new Fn('aaa'.18);
console.log(f1.constructor)  //Fn

/ / 2
function Fn(name,age){
    this.name=name;
    this.age=age;
}

Fn.prototype={
    say:function(){
        console.log(this)
        console.log('hello world')}}var f1=new Fn('aaa'.18);
console.log(f1.constructor)		/ / Object built-in classes

/ / 3
function Fn(name,age){
    this.name=name;
    this.age=age;
}

Fn.prototype={
    constructor:Fn,
    say:function(){
        console.log(this)
        console.log('hello world')}}var f1=new Fn('aaa'.18);
console.log(f1.constructor)				//Fn

Copy the code

Chain writing principle:

After executing a method, the result is still an instance of the current class, so you can continue to call other method operations of the current class (so the prototype extension method says return this).

Number (undefined) = NaN is false

Function distinct(arr){var obj={} for(var I =0; i<arr.length; i++){ var item=arr[i]; if(typeof obj[item] ! === 'undefined'){ arr[i] == arr[arr.length-1]; arr.length--; i--; } obj[item] = item; } obj = null; return arr; } var arr =,2,1,3,4,5,6,4,5,64,2,5,1,2,1 [1] the console. The log (distinct (arr))Copy the code
/ / in the prototype Array extension to heavy method. The prototype. MyDistinct = function myDistinct () {/ / this is arr (to deal with the current Array) so you can't preach ginseng var obj = {} for (var I = 0; i<this.length; i++){ var item=this[i]; if(typeof obj[item] ! === 'undefined'){ this[i] == this[this.length-1]; this.length--; i--; } obj[item] = item; } obj = null; return this; //=> implement the chain method, return the array, so that after executing this method, We can still continue to call in the array other method (not to consider the chain calls can not write)} var arr =,2,1,3,4,5,6,4,5,64,2,5,1,2,1 [1] arr. MyDistinct ()Copy the code
Arr. Sort (function(a,b){function(a,b){retrun a-b; }) arr.push(100) || || \/ arr.sort(function(a,b){ retrun a -b; }).push(100) //arr.push() returns the length of the array after the pushCopy the code

The sample

Prototype. Plus =function plus(){return this+arguments[0]; } Number.prototype.minus=function minus(){ return this-arguments[0]; } / / rigorous Considering the case Number. Don't preach and prototype. Plus = function plus () {var val = Number (the arguments [0]) | | 0; return this+val; } Number.prototype.minus=function minus(){ var val=Number(arguments[0]) || 0; return this-val; }Copy the code