有关原型的一些方法

整理一下有关原型或者原型链上常出的一些方法

1. istancenof

a instanceof b用来判断a的原型链上是否有b的存在

// instanceof
function Father(){
    this.sayFather = 'i am father'
}
function Son(){
    this.saySon = 'i am son'
};
Son.prototype = new Father();
var son = new Son();
console.log(son instanceof Son) // true
console.log(son instanceof Father) // true
console.log(son instanceof Number) // false
console.log(son instanceof Object) // true
console.log(Father instanceof Object) // true

2. isPrototypeOf

isPrototypeOf() 方法用于测试一个对象是否存在于另一个对象的原型链上。

function Father(){
    this.sayFather = 'i am father'
}
function Son(){
    this.saySon = 'i am son'
};
Son.prototype = new Father();
var son = new Son();
console.log(Son.isPrototypeOf(son)) // false
console.log(Son.prototype.isPrototypeOf(son)) // true
console.log(Father.prototype.isPrototypeOf(son)) // true
console.log(Number.prototype.isPrototypeOf(son)) // false
console.log(Object.prototype.isPrototypeOf(son)) // true
console.log(Object.prototype.isPrototypeOf(Father)) // true

instanceisPrototypeOf的区别是:instance是比较b.prototype的,而isPrototoyeOf是比较本身

3. getPrototypeOf

Object.getPrototypeOf() 方法返回指定对象的原型(内部[[Prototype]]属性的值)。

Son.prototype = new Father();
var son = new Son();
console.log(Object.getPrototypeOf(son.__proto__) === Father.prototype ) // true
console.log(Object.getPrototypeOf(son) === Son.prototype) // true
console.log(Object.getPrototypeOf(son) === Father.prototype) // false

4. hasOwnProperty

会返回一个布尔值,指示对象自身属性中是否具有指定的属性(也就是,是否有指定的键)

function Father(){
    this.sayFather = 'i am father'
}
function Son(){
    this.saySon = 'i am son'
};
Son.prototype = new Father();
var son = new Son();
console.log(son.saySon) // i am son
console.log(son.sayFather) // i am father
console.log(son.hasOwnProperty('saySon')) // true
console.log(son.hasOwnProperty('sayFather')) // false
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值