JS: hasOwnProperty 和 in和 在prototype上添加方法
一、hasOwnProperty和in
1、hasOwnProperty方法可以檢查物件是否真正“自己擁有”某屬性或者方法
2、in運算子只能檢查某個屬性或方法是否可以被物件訪問,不
能檢查是否是自己的屬性或方法
function People(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
// 往原型上添加nationality屬性
People.prototype.nationality = '中國';
//實體化
var xiaoming = new People('小明', 12, '男');
console.log(xiaoming.hasOwnProperty('name')); //true
console.log(xiaoming.hasOwnProperty('age')); //true
console.log(xiaoming.hasOwnProperty('sex')); //true
console.log(xiaoming.hasOwnProperty('nationality')); //false
console.log('name' in xiaoming); //true
console.log('age' in xiaoming); //true
console.log('sex' in xiaoming); //true
console.log('nationality' in xiaoming); //true
二、在prototype上添加方法
1.添加方法,毫無疑問,我們可以直接加在實體上
function People(name, age, sex){
this.name = name;
this.age = age;
this.sex = sex;
this.sayHello = function(){ //方法直接添加 到實體身上
console.log('我是' + this.name);
};
}

function People() {
this.sayHello = function () {};
}
var xiaoming = new People();
var xiaohong = new People();
var xiaogang = new People();
console.log(xiaoming.sayHello === xiaohong.sayHello); //false
缺點:每個實體和每個實體的方法函式都是記憶體中不同的函式,造成了記憶體的浪費
**解決辦法:**將方法寫到prototype上
2.解決方法:將方法寫到prototype上

根據原型鏈查找:實體可以打點訪問它的原型的屬性和方法
function People(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
// 把方法要寫到原型上
People.prototype.sayHello = function () {
console.log('你好,我是' + this.name + '我今年' + this.age + '歲了');
}
People.prototype.growup = function () {
this.age++;
}
var xiaoming = new People('小明', 12, '男');
var xiaohong = new People('小紅', 11, '女');
console.log(xiaoming.sayHello === xiaohong.sayHello);
//true 同一個sayHello可以被小明小紅同時呼叫
xiaoming.sayHello(); //你好,我是小明我今年12歲了
xiaohong.sayHello(); //你好,我是小紅我今年11歲了
xiaoming.growup();
xiaoming.growup();
xiaoming.growup();
xiaoming.growup();
xiaoming.growup(); //你好,我是小明我今年17歲了
xiaoming.sayHello();
xiaohong.sayHello(); //你好,我是小紅我今年11歲了
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/401660.html
標籤:其他
上一篇:JS:原型鏈、原型鏈的查找、原型鏈的遮蔽效應、原型鏈的終點、關于陣列的原型鏈
下一篇:給網站添加訪問地圖3d版,平面版
