zoukankan      html  css  js  c++  java
  • instanceof 的作用

    instanceof 运算符用来测试一个对象在其原型链中是否存在一个构造函数的 prototype 属性.

    语法

      object instanceof constructor

    从语法的字面意思来理解就是 某一个对象是否有该构造器生成

    从实际效果上来讲,instanceof 运算符用来检测 constructor.prototype 是否存在于参数 object 的原型链 ( __proto__ ) 上

    也可以用js来替代  constructor.prototype.isPrototypeOf( object )

    通过js脚本来实现 instanceof 运算符:

      

    function _instanceof( object,cons ){
        if( object.__proto__ !== null ){
            if( object.__proto__ == cons.prototype ){
                return true
            }
            return _instanceof( object.__proto__ , cons )
        }
        return false
    }
    
    function A(){}
    
    var c = new A()
    _instanceof(c,A);//true
    _instanceof(c,Object);//true

    例子:

    // 定义构造函数
    function C(){} 
    function D(){} 
    
    var o = new C();
    
    
    o instanceof C; // true,因为 Object.getPrototypeOf(o) === C.prototype
    
    
    o instanceof D; // false,因为 D.prototype不在o的原型链上
    
    o instanceof Object; // true,因为Object.prototype.isPrototypeOf(o)返回true
    C.prototype instanceof Object // true,同上
    
    C.prototype = {};
    var o2 = new C();
    
    o2 instanceof C; // true
    
    o instanceof C; // false,C.prototype指向了一个空对象,这个空对象不在o的原型链上.
    
    D.prototype = new C(); // 继承
    var o3 = new D();
    o3 instanceof D; // true
    o3 instanceof C; // true
    

      

  • 相关阅读:
    kubernetes
    dubbo
    前端控件+资源
    Gossip
    问题解决1
    react
    impala
    storm+Calcite
    ASP.NET页面传值与跳转
    经典FormsAuthenticationTicket 分析
  • 原文地址:https://www.cnblogs.com/xiaxiaodong/p/8276836.html
Copyright © 2011-2022 走看看