hasOwnProperty与isPrototypeOf

时间:2023-03-09 06:28:48
hasOwnProperty与isPrototypeOf
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>hasOwnProperty与isPrototypeOf</title>
</head>
<body>
<script>
// hasOwnProperty:是用来判断一个对象是否有你给出名称的属性或对象。不过需要注意的是,此方法无法检查该对象的原型链中是否具有该属性,该属性必须是对象本身的一个成员。
// isPrototypeOf:是用来判断要检查其原型链的对象是否存在于指定对象实例中,是则返回true,否则返回false。
function person(firstName,lastName) {
this.firstName=firstName;
this.lastName=lastName;
}
person.prototype.setName=function(){
return this.firstName+','+this.lastName
}
var jone=new person('jone','chen');
jone.age=30
console.log(jone.setName()); // ==>jone,chen
console.log(jone.hasOwnProperty('setName')) // ==>false
console.log(jone.hasOwnProperty('age')) // ==>true
console.log(jone.hasOwnProperty('firstName')) // ==>true
console.log(person.prototype.isPrototypeOf(jone)); // ==>true
console.log(person.prototype.isPrototypeOf('jone')); // ==>false
</script>
</body>
</html>

hasOwnProperty:是用来判断一个对象是否有你给出名称的属性或对象。不过需要注意的是,此方法无法检查该对象的原型链中是否具有该属性,该属性必须是对象本身的一个成员。

isPrototypeOf:是用来判断要检查其原型链的对象是否存在于指定对象实例中,是则返回true,否则返回false。

var person = function (work) {
this.work = work;
};
person.prototype.name = "jone";
person.prototype.age = 30;
person.prototype.say = function () {
console.log(this.name + ',' + this.age + ',' + this.work)
}
var jone = new person("xuesheng");
jone.say();
console.log(person.prototype.hasOwnProperty('name'));
console.log(person instanceof Object);
console.log(jone.hasOwnProperty('work'))
console.log(person.prototype.hasOwnProperty('work'))
console.log(person.prototype.isPrototypeOf(jone))