JS: hasOwnProperty 和 in和 在prototype上添加方法

JS: hasOwnProperty 和 in和 在prototype上添加方法

一、hasOwnPropertyin
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岁了

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>