I. typeof operator
typeof
operator is used to return the type of the value being used.
// 使用原始值let mNull = null;let mUndefined = undefined;let mString = ‘mazey‘;let mNumber = 123;let mBoolean = true;let mFunction = function () { return true;};// 用构造函数的方式new一个实例let oString = new String(‘cherrie‘);let oRegExp = new RegExp(‘^[0-9]+$‘);let oFunction = new Function(‘x‘, ‘y‘, ‘return x + y‘);let oObj = {};let oNew = new Object();// typeof值console.log(typeof mNull); // objectconsole.log(typeof mUndefined); // undefinedconsole.log(typeof mString); // stringconsole.log(typeof mNumber); // numberconsole.log(typeof mBoolean); // booleanconsole.log(typeof mFunction); // functionconsole.log(typeof oString); // objectconsole.log(typeof oRegExp); // objectconsole.log(typeof oFunction); // functionconsole.log(typeof oObj); // objectconsole.log(typeof oNew); // object
The introduction in the JavaScript Apocalypse new RegExp()
will return function
, but in fact what I see in the Chrome console is object
.
So I console.log(new RegExp(‘^[0-9]+$‘))
, printed out is the string /^[0-9]+$/
.
console.log(new RegExp(‘^[0-9]+$‘)); // /^[0-9]+$/console.log(RegExp); // ƒ RegExp() { [native code] } 原始值console.log(String); // ƒ String() { [native code] } 原始值console.log(/^[0-9]+$/); // /^[0-9]+$/console.log(new RegExp(‘^[0-9]+$‘) === /^[0-9]+$/); // falseconsole.log(RegExp(‘^[0-9]+$‘) === /^[0-9]+$/); // false
You can see RegExp
that the current version String Number
is the same as the original value of JavaScript.
Math
What does it return as a static object in JavaScript?
console.log(typeof Math); // objectconsole.log(typeof Math.PI); // numberconsole.log(typeof Math.ceil); // function
As a result Math
__proto__
, Object
you typeof
can also return the object's properties and types of methods.
typeof Usage Scenarios
1. Determine if a variable is defined
console.log(typeof aaa); // ‘undefined‘// 判断if (typeof bbb === ‘undefined‘) { console.log(‘变量未定义‘);}
2. Distinguish between original and complex values (object values)
Because complex values tend to return, there is, of course, an object
exception where the original value is null
returned object
, and then function
Object
The instance is also a complex value.
// 判断是否时复杂值(对象值)function isObject (m) { return (typeof m === ‘function‘ || (typeof m === ‘object‘ && m !== null));}console.log(isObject(new RegExp(‘123‘))); // trueconsole.log(isObject(‘123‘)); // falseconsole.log(isObject(String(‘123‘))); // falseconsole.log(isObject(null)); // false// 判断是否是原始值function isNative (m) { return (m === null || (typeof m !== ‘object‘ && typeof m !== ‘function‘));}console.log(isNative(new RegExp(‘123‘))); // falseconsole.log(isNative(‘123‘)); // trueconsole.log(isNative(String(‘123‘))); // trueconsole.log(isNative(null)); // true
3. Detecting if a variable is a function
When a closure is used, the function is determined before the next step.
function qqq () { let a = 0; let b = function () { a++; console.log(a); }; return b;}let ccc = qqq();console.log(typeof ccc); // functionif (typeof ccc === ‘function‘) { ccc(); // 1 ccc(); // 2 ccc(); // 3 ccc(); // 4}
Two. instanceof operator
By using instanceof
an operator, you can determine whether an object is an instance of a particular constructor , true
or Return or false
.
instanceof
Applies only to constructors to create complex objects and instances that are returned.
Any time you judge whether an object (complex value) is an Object
instance, it is returned true
because all objects inherit from the Object()
constructor.
let oFather = function () { this.firstName = ‘mazey‘;};oFather.prototype.lastName = ‘qian‘;// 实例let oSon = new oFather();console.log(oSon instanceof oFather); // true// 继承let nFather = function () {};nFather.prototype = new oFather();nFather.construction = nFather;console.log(nFather.firstName); // undefinedconsole.log(nFather.prototype.lastName); // qianconsole.log(nFather instanceof oFather); // falseconsole.log(new nFather() instanceof nFather); // true// 相对于Object来说console.log(‘123‘ instanceof Object); // falseconsole.log(new String(‘123‘) instanceof Object); // true 构造出来的实例console.log(null instanceof Object); // false
instanceof Usage Scenarios
Determines whether an instance belongs to its parent class in an inheritance relationship.
// 继承let oFather = function () {};let nFather = function () {};nFather.prototype = new oFather();nFather.construction = nFather;let nSon = new nFather();console.log(nSon instanceof nFather); // trueconsole.log(nSon instanceof oFather); // true
Three. In operator and hasOwnProperty method
in
The operator can examine the properties of an object, including properties from the prototype chain, and the hasOwnProperty()
method can examine the objects from the non-prototype chain properties.
For example, there is an object let obj = {name: ‘mazey‘};
that name
is itself defined as an attribute that toString
is inherited from the prototype chain.
let obj = {name: ‘mazey‘};console.log(‘name‘ in obj); // trueconsole.log(‘toString‘ in obj); // trueconsole.log(‘name‘ in Object); // trueconsole.log(obj.hasOwnProperty(‘name‘)); // trueconsole.log(obj.hasOwnProperty(‘toString‘)); // falseconsole.log(Object.hasOwnProperty(‘name‘)); // true
So the in operator looks a little wider and can be hasOwnProperty()
judged by whether it is a property of the object itself, rather than by a similar obj.prototype.foo = ‘foo‘;
definition.
hasOwnProperty Method Usage Scenarios
It is often used in real projects for...in...
to iterate through the enumerable properties of an object, but for...in...
often the attributes in the prototype obj.prototype.xxx
are enumerated, so the method can be judged at the time of the loop hasOwnProperty()
.
function obj0 () { this.name = ‘mazey‘, this.age = ‘24‘};obj0.prototype.gender = ‘male‘;let obj1 = new obj0();// 打印所有可枚举属性for (let key in obj1) { console.log(key); // name age gender 从原型链上继承下来的属性也会被打印出来}// 过滤掉原型链上的属性for (let key in obj1) { if (obj1.hasOwnProperty(key)) { console.log(key); // name age }}
Four. Summary
1. typeof
You can determine the type of value used, and be careful to null
return object
. 2. instanceof
Verify that the constructor constructs an instance that can be used to determine whether an object belongs to a parent class. 3. hasOwnProperty
methods are often in
used in conjunction with operators to traverse the properties of an object itself.
Five. Related extensions 1. Delete an object's properties
To remove an object's own attributes completely, use the delete
operator.
let obj0 = { name: ‘mazey‘, age: 24};// 删除age属性delete obj0.age;console.log(obj0.hasOwnProperty(‘age‘)); // falseconsole.log(‘age‘ in obj0); // false// 试着删除原型链上的属性 toStringdelete obj0.toStringconsole.log(‘toString‘ in obj0); // true
It is important to note that the delete
properties on the prototype chain are not deleted.
2. Enumerable
The properties of each object are categorized into enumerable and non-enumerable properties, and you can use propertyIsEnumerable()
methods to check which properties are enumerable.
Each object has a propertyIsEnumerable
method. This method can determine whether the specified property in the object can be for...in
(the for...in statement iterates through an enumerable property of an object in any order .) For each different attribute, the statement is executed), except for attributes inherited through the prototype chain. If the object does not have a specified property, this method returns false
.
Some data say that as long as the property that can be for..in
traversed is enumerable, in fact, to exclude from the prototype chain inherited properties, only its own properties are enumerable.
//First constructor function ConFun0 () {this.firstname = ' Mazey ';} ConFun0.prototype.firstCom = ' bang ';//second constructor function ConFun1 () {this.secondname = ' qian ';} Inherit the first confun1.prototype = new ConFun0 (); ConFun1.prototype.constructor = confun1;//instance Let obj = new ConFun1 () Obj.girlname = ' Cherrie ';//Can enumerate Console.log ( Obj.propertyisenumerable (' constructor ')); Falseconsole.log (obj.propertyisenumerable (' firstName ')); Falseconsole.log (obj.propertyisenumerable (' firstcom ')); false//attributes inherited through the prototype chain are not enumerable Console.log (obj.propertyisenumerable (' secondname ')); Trueconsole.log (obj.propertyisenumerable (' girlname ')); Truefor (let key in obj) {console.log (key);//Secondname Girlname (the properties on the prototype chain will also be printed) FirstName constructor firs Tcom}console.log ('---split line---'); for (let key in obj) {//filter out the properties on the prototype chain if (Obj.hasownproperty (key)) {Console.log (key); Secondname Girlname}}
So an enumerable property must be iterated through for..in
, but a for...in
loop-traversed property is not necessarily enumerable, and attributes inherited from the prototype chain need to be excluded, and the hasOwnProperty()
non-enumerable property can be filtered out of the method.
The usage and difference of typeof,instanceof,hasownproperty,in in JavaScript
The usage and difference of typeof,instanceof,hasownproperty,in in JavaScript