Related methods and strict patterns of Object objects

Posted by insane on Sat, 18 Dec 2021 13:06:31 +0100

1, Object object related methods

Object. The getprototypeof method returns the prototype of the parameter object. This is the standard way to get prototype objects.

The prototype of the instance object f is the prototype property of the constructor

Prototypes of several special objects

// The prototype of an empty object is object prototype
Object.getPrototypeOf({}) === Object.prototype // true

// Object. The prototype of prototype is null
Object.getPrototypeOf(Object.prototype) === null // true

// The prototype of the function is function prototype
function f() {}
Object.getPrototypeOf(f) === Function.prototype // true

1.1Object.setPrototypeOf method

Set the prototype for the parameter object and return the parameter object. It accepts two parameters, the first is an existing object and the second is a prototype object

var a = {};
var b = {x: 1};
Object.setPrototypeOf(a, b);

Object.getPrototypeOf(a) === b // true
a.x // 1

The new command can use object Setprototypeof method simulation.

var F = function () {
  this.foo = 'bar';
};

var f = new F();
// Equivalent to
var f = Object.setPrototypeOf({}, F.prototype);
F.call(f);

The first step is to set the prototype of an empty object as the prototype property of the constructor (F.prototype in the above example); the second step is to bind this inside the constructor to the empty object, and then execute the constructor so that the methods and properties defined on this (this.foo in the above example) are transferred to the empty object

1.2Object.create()

A common way to generate an instance object is to use the new command to let the constructor return an instance

Object.create() method, which takes an object as a parameter, and then takes it as the prototype to return an instance object. The instance fully inherits the properties of the prototype object

// Prototype object
var A = {
  print: function () {
    console.log('hello');
  }
};

// Instance object
var B = Object.create(A);

Object.getPrototypeOf(B) === A // true
B.print() // hello
B.print === A.print // true

Object. The create () method can be replaced by the following code

if (typeof Object.create !== 'function') {
  Object.create = function (obj) {
    function F() {}
    F.prototype = obj;
    return new F();
  };
}

Object. The essence of the create () method is to create an empty constructor F, then point the F.prototype attribute to the parameter object obj, and finally return an instance of F, so as to enable the instance to inherit the attributes of obj

The new objects generated by the three methods are equivalent.
var obj1 = Object.create({});
var obj2 = Object.create(Object.prototype);
var obj3 = new Object();

If you want to generate an object that does not inherit any properties (such as no toString() and valueOf() methods), you can use object The parameter of create() is set to null

Object. When using the create () method, you must provide an object prototype, that is, the parameter cannot be empty or not an object, otherwise an error will be reported.

Any method added or modified on the prototype will be immediately reflected on the new object.

Object. The create () method can also accept the second parameter. This parameter is a property description object. The object properties described by it will be added to the instance object as the properties of the object itself.

Object. The object generated by the create () method inherits the constructor of its prototype object.

1.3 isPrototypeOf method

Used to determine whether the object is the prototype of the parameter object.
The isPrototypeOf method returns true as long as the instance object is on the prototype chain of the parameter object.

Object.prototype.isPrototypeOf({}) // true
Object.prototype.isPrototypeOf([]) // true
Object.prototype.isPrototypeOf(/xyz/) // true
Object.prototype.isPrototypeOf(Object.create(null)) // false

Due to object Prototype is at the top of the prototype chain, so it returns true for various instances, except for objects directly inherited from null

1.4 __proto_ attribute

Instance object__ proto__ Property (two underscores before and after each) to return the prototype of the object. The property is readable and writable

var obj = {};
var p = {};

obj.__proto__ = p;
Object.getPrototypeOf(obj) === p // true

Pass__ proto__ Property to set the p object as the prototype of the obj object.

__ proto__ Property only browsers need to be deployed. Other environments can not have this property. The two underscores before and after it indicate that it is an internal attribute and should not be exposed to users. Therefore, it should be used as little as possible

__ proto__ Property points to the prototype object of the current object, that is, the prototype property of the constructor

There are three methods to obtain the prototype object of the instance object obj.

obj.proto
obj.constructor.prototype
Object.getPrototypeOf(obj) is recommended

__ proto__ Properties only need to be deployed in browsers, and other environments can not be deployed. And obj constructor. Prototype may fail when you manually change the prototype object.
When changing the prototype object, the constructor property should be set at the same time.

C.prototype = p;
C.prototype.constructor = C;

var c = new C();
c.constructor.prototype === p // true

1.5 getOwnPropertyNames()

Object. The getownpropertynames method returns an array whose members are the key names of all properties of the parameter object itself, excluding the inherited property key names.

Object. The getownpropertynames method returns all key names, whether traversable or not. Get only those properties that can be traversed, using object Keys method.

1.6Object.prototype.hasOwnProperty()

The hasOwnProperty method of an object instance returns a Boolean value, which is used to determine whether a property is defined as true on the object itself or false on the prototype chain

The hasOwnProperty method is the only method in JavaScript that does not traverse the prototype chain when processing object properties.

1.7 in operator and for... In loop

The in operator returns a Boolean value indicating whether an object has a property. It does not distinguish whether the property is an object's own property or an inherited property.

To get all the traversable properties of the object (whether self or inherited), you can use the for... in loop.

To obtain all the properties of the object (whether self or inherited, and whether enumerable or not), you can use the following function.

function inheritedPropertyNames(obj) {
  var props = {};
  while(obj) {
    Object.getOwnPropertyNames(obj).forEach(function(p) {
      props[p] = true;
    });
    obj = Object.getPrototypeOf(obj);
  }
  return Object.getOwnPropertyNames(props);
}

1.8 copy of objects

If you want to copy an object, you need to do the following two things.

Ensure that the copied object has the same prototype as the original object.
Ensure that the copied object has the same instance properties as the original object.

function copyObject(orig) {
  var copy = Object.create(Object.getPrototypeOf(orig));
  copyOwnPropertiesFrom(copy, orig);
  return copy;
}

function copyOwnPropertiesFrom(target, source) {
  Object
    .getOwnPropertyNames(source)
    .forEach(function (propKey) {
      var desc = Object.getOwnPropertyDescriptor(source, propKey);
      Object.defineProperty(target, propKey, desc);
    });
  return target;
}

The simple way to write it is to use ES2017 to introduce the standard object Getownpropertydescriptors method.

function copyObject(orig) {
  return Object.create(
    Object.getPrototypeOf(orig),
    Object.getOwnPropertyDescriptors(orig)
  );
}

2, Strict mode

The strict mode enters the standard from ES5. The main purposes are as follows.

Explicitly prohibit some unreasonable and lax syntax and reduce some strange behaviors of JavaScript language.
Add more error reporting occasions, eliminate some unsafe places in code operation, and ensure the safety of code operation.
Improve the efficiency of the compiler and increase the running speed.
Pave the way for a new version of JavaScript syntax in the future.

The sign for entering strict mode is a line of string use strict.

'use strict';

Strict mode can be used for the entire script or only for a single function.

(1) Entire script file

use strict is placed on the first line of the script file, and the entire script will run in strict mode.

(2) Single function

If use strict is placed on the first line of the function body, the whole function runs in strict mode.

If the scripts in strict mode are first, the merged scripts are all in strict mode; If the scripts in normal mode are first, the merged scripts are in normal mode. In both cases, the combined results are incorrect. At this point, consider putting the entire script file in an anonymous function that executes immediately.

2.1 explicit error reporting

Strict mode makes the syntax of JavaScript more strict, and more operations will explicitly report errors

  • In strict mode, an error will be reported when assigning a value to a read-only attribute or deleting a non configurable attribute.
  • Only properties with accessors set are not writable
  • Objects prohibited from extension are not extensible
  • eval and arguments cannot be used as identity names
  • Functions cannot have parameters with duplicate names (in normal mode, if a function has multiple parameters with duplicate names, it can be read with arguments[i]. In strict mode, this is a syntax error.)
  • Prohibit prefix 0 notation in octal
  • Global variables must be declared explicitly. (in strict mode, variables must be declared before use)
  • Prohibit this keyword from pointing to global objects
  • In strict mode, When the function is called directly (new call is not used), this inside the function indicates undefined (undefined), so you can use call, apply and bind methods to bind any value to this. In normal mode, this points to a global object. If the bound value is a non object, it will be automatically converted to an object and then bound. null and undefined values that cannot be converted to an object will be ignored

    // Normal mode
    function fun() {
      return this;
    }
    
    fun() // window
    fun.call(2) // Number {2}
    fun.call(true) // Boolean {true}
    fun.call(null) // window
    fun.call(undefined) // window
    
    // Strict mode
    'use strict';
    function fun() {
      return this;
    }
    
    fun() //undefined
    fun.call(2) // 2
    fun.call(true) // true
    fun.call(null) // null
    fun.call(undefined) // undefined
    
    
  • FN. Cannot be used inside a function caller,fn.arguments
  • Arguments. Is prohibited callee,arguments.caller
  • It is forbidden to delete variables. Variables cannot be deleted in strict mode. If you use the delete command to delete a variable, an error will be reported. Only the attribute of the object and the configurable attribute of the description object are set to true can be deleted by the delete command.
  • 'use strict';
    var x;
    delete x; // syntax error
    
    var obj = Object.create(null, {
      x: {
        value: 1,
        configurable: true
      }
    });
    delete obj.x; // Delete succeeded
    

    2.2 static binding

    In some cases, only static binding is allowed. In other words, the object to which attributes and methods belong must be determined at the compilation stage

  • The with statement is prohibited
  • var a = obj.a;
    var b = obj.b;
    var c = obj.c;
    
    with(obj){
        var a = a;
        var b = b;
        var c = c;
    
    
  • Create Eval scope in normal mode, JavaScript language has two variable scopes: global scope and function scope. Strict mode creates the third scope: Eval scope. The variables generated by Eval can only be used inside eval.
  • arguments no longer tracks changes in parameters
  • Non functional code blocks must not declare that the function ES5 environment will report an error. Note that if it is an ES6 environment, the above code will not report an error, because ES6 allows functions to be declared in code blocks
  • Reserved words in order to transition to the new version of JavaScript in the future, some reserved words (implements, interface, let, package, private, protected, public, static, yield, etc.) have been added in the strict mode. Using these words as variable names will report errors.

Topics: Javascript