JS中原型的一些判断方法

判断某个属性是否在自己上面,而不是在原型上(hasOwnProperty)

var obj = {
    name : 'why',
    age : 18
}

var info = Object.create(obj,{ //第二个属性传的是属性描述符
    address:{
        value:'北京市',
        enumerable:true
    }
})

console.log(info); //{ address: '北京市' } 
console.log(info.__proto__);{ name: 'why', age: 18 }

//判断某个属性是否在自己上面,而不是原型上
console.log(info.hasOwnProperty('address'));  //true
console.log(info.hasOwnProperty('age'));  //false

不管是不是在原型上,只要存在就是true(in操作符)

var obj = {
    name : 'why',
    age : 18
}

var info = Object.create(obj,{ //第二个属性传的是属性描述符
    address:{
        value:'北京市',
        enumerable:true
    }
})
console.log("address" in info); //true
console.log("name" in info); //true

检测构造函数的prototype是否出现在某一对象的原型上(instanceof)

//instanceof(其实用的也不是特别多)
//用于检测构造函数的prototype,是否出现在某一对象的原型上

//继承的函数
function inheritPrototype(SubType,SuperType){
    SubType.prototype = Object.create(SuperType.prototype) 
    Object.defineProperty(SubType.prototype,"constructor",{
        enumerable:false,
        configurable:true,
        writable:true,
        value:SubType
    })
}

function Person(){

}

function Student(){

}

inheritPrototype(Student,Person)

var stu = new Student() 
//这个是比较符合事实逻辑的
console.log(stu instanceof Student);  //true,原型对象(prototype)是在原型链里的
console.log(stu instanceof Person); //true student也是人 
console.log(stu instanceof Object); //true  student也是Object衍生的

来自本人掘金文章:https://juejin.cn/post/7111857552182214663/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值