這兩個單詞猛地一看,感受很像,也容易讀錯。今天抽空來總結一下關於它們的一些不經常使用,可是很重要的方法。數組
prototype: ['proʊtə.taɪp] 原型
property: ['prɑpərti] 屬性
複製代碼
這裏就是檢測Object.prototype這個對象是否在object的原型鏈上,返回true或false,固然若是Object.prototype是undefined或null也會報錯函數
function Person(){} //構造函數
function Parent(){} //構造函數
const person1 = new Person(); //實例化一個對象person1
const child = new Parent(); //實例化一個對象child
console.info(Person.prototype.isPrototypeOf(person1));//true
console.info(Person.prototype.isPrototypeOf(child));//false
複製代碼
這裏表示獲取obj的原型。this
function Person(){}
const person = new Person();
console.log(Object.getPrototypeOf(person)); //Person.prototype
複製代碼
var obj = {
name:'Nicholas',
age:18
};
console.log(obj.hasOwnProperty('name'))//true
var obj1 = {};
obj1.name = 'lily';
console.log(obj1.hasOwnProperty('name'));//true
delete obj1.name;
console.log(obj1.hasOwnProperty('name'));//false
function Person(){}
Person.prototype.name = 'nicholas';
var p1 = new Person();
console.log(p1.hasOwnProperty('name'));//false
console.log(Person.prototype.hasOwnProperty('name'));//true
複製代碼
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype.job = 'teacher';
const p1 = new Person('Nicholas',18);
console.log('name' in p1)//true
console.log('job' in p1); //true
delete Person.prototype.job;
console.log('job' in p1);//false
var arr = ['jj','kk'];
0 in arr; //true 0是索引,是數組的屬性
var str = 'kkl';
length in str //false 由於str不是對象
複製代碼
function isPrototypeProp(obj,prop){
return !obj.hasOwnProperty(prop) && prop in obj;
}
var obj = {};
console.log(isPrototypeProp(obj,'toString')); //true
複製代碼