關於prototype和property的一些不經常使用的方法

這兩個單詞猛地一看,感受很像,也容易讀錯。今天抽空來總結一下關於它們的一些不經常使用,可是很重要的方法。數組

怎麼讀,是什麼

prototype: ['proʊtə.taɪp]  原型
property:  ['prɑpərti]     屬性
複製代碼

不經常使用的方法

  • 1.Object.prototype.isPrototypeOf(obj);
  • 2.Object.getPrototypeOf(obj);
  • 3.obj.hasOwnProperty();
  • 4.prop in obj;

1.Object.prototype.isPrototypeOf(object)

用來檢測一個對象是否在另外一個對象的原型鏈上;

這裏就是檢測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
複製代碼

2.Object.getPrototypeOf(obj)

用來獲取一個對象的原型;

這裏表示獲取obj的原型。this

function Person(){}
const person = new Person();
console.log(Object.getPrototypeOf(person)); //Person.prototype
複製代碼

3. obj.hasOwnProperty(prop)

用來判斷某個對象是不是存在指定的屬性,而不是經過原型鏈找到的屬性

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
複製代碼

4. in 運算符

用來判斷對象中或是它的原型對象中是否存在指定的屬性

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不是對象
複製代碼

經過obj.hasOwnProperty()和in操做符,能夠封裝出判斷是原型的屬性的方法

function isPrototypeProp(obj,prop){
    return !obj.hasOwnProperty(prop) && prop in obj;
}


var obj = {};
console.log(isPrototypeProp(obj,'toString')); //true
複製代碼
相關文章
相關標籤/搜索