javascript - instanceof operator
黄舟
黄舟 2017-05-19 10:26:43
0
3
678

https://www.ibm.com/developer...

According to this article

instaceof can be simulated with the following code

function instance_of(L, R) {//L 表示左表达式,R 表示右表达式
  var O = R.prototype;// 取 R 的显示原型
  L = L.__proto__;// 取 L 的隐式原型
  while (true) { 
    if (L === null) 
      return false; 
    if (O === L)// 这里重点:当 O 严格等于 L 时,返回 true 
      return true; 
    L = L.__proto__; 
  } 
 }
     

But
var a=1;
instance_of(a,Object) is true
a instanceof Object returns false, why is this?

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(3)
伊谢尔伦

Owner, you can try your instance_of 是代替不了 instanceof’s

First, make sure that your sample a is of type Number

However, the execution result is as follows
instance_of(a, Object) // true
instance_of(a, Number) // true

Modify instance_of method:

function instance_of(L, R) {
  try {
    var O = R.prototype;// 取 R 的显示原型
    L = Object.getPrototypeOf(L);// 取 L 的隐式原型
    while (true) { 
      if (L === null) 
        return false; 
      if (O === L)// 这里重点:当 O 严格等于 L 时,返回 true 
        return true; 
      L = L.Object.getPrototypeOf(L); 
    }
  } catch (e) {
    return false
  }
}

Experiment again:

var a = 1

instance_of(a, Object) // false 
instance_of(a, Number) // true

var parent = function () {}  
var child = new parent()

instance_of(child, parent) // true
世界只因有你

The standard used in this article is ES3

ES6’s instanceof标准更长一点, 规定了当type(L)不是Object时L instanceof R should return false. This mock code does not apply

曾经蜡笔没有小新

One part is the content of the prototype chain, in your simulation code:

    function instance_of(L, R) {//L 表示左表达式,R 表示右表达式
      var O = R.prototype;// 取 R 的显示原型
      L = L.__proto__;// 取 L 的隐式原型
      while (true) { 
        if (L === null) 
          return false; 
        if (O === L)// 这里重点:当 O 严格等于 L 时,返回 true 
          return true; 
          L = L.__proto__; 
       } 
     }

L = L._proto_ 代表着L会沿着原型链一直向上查找原型,而在本例中,最后是从Number包装对象==>Object对象,而R就是Object,再经过全等运算符之后就返回true,所以instance_of(a,Object) is true.

a instanceof ObjectReturns false because it does not go through the prototype chain search, it is directly judged between the instance of the Number object and the Object, so the result is false

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!