当前位置:网站首页>Prototype and prototype chain - constructor and instanceof

Prototype and prototype chain - constructor and instanceof

2022-06-25 13:22:00 wendyTan10

instanceof Determine the value type

Type judgment

typeof Is used to determine all value types ,( Return data type : undefinedstringbooleannumbersymbol(ES6)ObjectFunction) Can identify reference types , But you can't distinguish object And Array The type of

var list = [];
console.log(typeof list); // object

How to determine the type of array , Use instanceofinstanceof The essence of is detection Prototype chain , Operators are used to determine the type of value .instanceof Operator returns a Boolean value boolean, Indicates whether an object is an instance of the specified constructor .

var d = new Date();
d instanceof Date // true
d instanceof Object // true

notes : about undefined and null,instanceOf Operator always returns false.

undefined instanceof Object // false
null instanceof Object // false

Constructors

Constructors It is created in the same way as normal functions , It's customary to capitalize ; Used to create a new instance object

function Person(name){
    
     this.name=name;
     this.sayHi = function() {
    
          alert("Hi")
     }
 }
var student1= new Person('wendy');
var student2= new Person('kim');
student1.name; // 'wendy'
student1.sayHi(); //

** shortcoming :** Between multiple instances of the same constructor , Can't share properties , So as to cause the waste of system resources .

prototype Attribute function of prototype

JavaScript Each object of the object inherits another object , The latter is called “ Prototype ”(prototype) object . One side , Any object , Can be used as the prototype of other objects ; On the other hand , Because the prototype object is also an object , So it has its own prototype .null It can also serve as a prototype , The difference is that it doesn't have its own prototype object .
Each constructor has one prototype attribute , This property will be used when generating instances , Become the prototype object of the instance object .
JavaScript The design of inheritance mechanism is , All properties and methods of the prototype , Can be shared by child objects ; Inheritance mechanism of prototype chain ;
 Insert picture description here

constructor Properties of

prototype The object has a constructor attribute , The default point to prototype The constructor where the object resides
because constructor Property defined in prototype The above object , It means that it can be inherited by all instance objects .

function P() {
    }
P.prototype.constructor === P // true

var p = new P();
// function P() {}
p.constructor === P.prototype.constructor
// true
p.hasOwnProperty('constructor')
// false

Click to enter : Introduction to prototype and prototype chain

原网站

版权声明
本文为[wendyTan10]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202200525276018.html