function Person() {
}
Person.prototype.name="Nicholas";
Person.prototype.age=29;
Person.prototype.say=function () {
console.log(this.name);
}
var person1=new Person();
person1.say();
var person2=new Person();
person2.say();
//isPrototypeOf() 检测对象之间是否存在[Prototype]关系
console.log(Person.prototype.isPrototypeOf(person1)); //true
//ECMAScript5 新增了getPrototype() 返回[Prototype]的值
console.log(Object.getPrototypeOf(person1)==Person.prototype); //true
console.log(Object.getPrototypeOf(person1).age);//true;
//通过对象实例访问保存在原型中的值,但不能通过对象实例重写原型中的值
//在实例中创建同名属性,该属性会屏蔽原型中的那个属性
//hasOwnProperty()(这个方法从Object 继承)只在给定属性存在于对象实例中,才返回true
//in 操作符会在通过对象访问给定属性时候返回true
person1.age=111;
console.log(person1.age);//30 ---来自实例
console.log(person1.hasOwnProperty("age")); //hasOwnProperty true
console.log("age" in person1); //in true
console.log(person2.age);//29 ---来自原型
console.log(person2.hasOwnProperty("age")); //hasOwnProperty false
console.log("age" in person2); //in true
//delete 操作符可以完全删除实例
delete person1.age;
console.log(person1.age);//29 ---来自实例
console.log(person1.hasOwnProperty("age"));//hasOwnProperty false
console.log("age" in person2); //in true
console.log(person2.age);//29 ---来自原型
console.log(person2.hasOwnProperty("age"));//hasOwnProperty false
console.log("age" in person2); //in true
//同时使用hasOwnProperty()方法 和in操作符,就可确定该对象存在于对象中,还是原型中
function hasProperty(property,object) {
return !object.hasOwnProperty(property)&&(property in object); // ! 否定(相反)
}
function DataPerson(age) {
this.age=age;
}
DataPerson.prototype.name="Tom";
var dataPerson = new DataPerson(11)
console.log("判断"+hasProperty('age', dataPerson)); //false 来自实例
console.log("判断"+hasProperty('name',dataPerson)); //true 来自原型
//hasPrototypeProperty(),存在于原型返回true,不存在返回false
// console.log(hasPrototypeProperty(person1,"name")); 测不出来
967

被折叠的 条评论
为什么被折叠?



