⭐️ hasOwnProperty 返回自身非原型的属性

for...in 会把原型上的属性也遍历

function Car() {
	this.brand = 'Benz';
  this.color = 'red';
  this.displacement = '3.0';
}
Car.prototype = {
	lang: 5,
  width: 2.5
}
Object.prototype.name = 'Object';
var car = new Car();
for(var key in car) {
	console.log(key + ': ' + car[key]);
}

Untitled

hasOwnProperty 仅打印自身属性

function Car() {
	this.brand = 'Benz';
  this.color = 'red';
  this.displacement = '3.0';
}

Car.prototype = {
	lang: 5,
  width: 2.5
}

Object.prototype.name = 'Object';
var car = new Car();
for(var key in car) {
  if(car.hasOwnProperty(key)) {
		console.log(key + ': ' + car[key])
  }
}

Untitled

'属性名称' in 对象

判断属性是否在对象内(原型上的也算

var car = {
	brand: 'Benz',
	color: 'red'
}

console.log('displacement' in car);
console.log('color' in car);

Untitled

⭐️ in 不会排除对象原型上属性

function Car() {
	this.brand = 'Benz';
	this.color = 'red';
	this.displacement = '3.0';
}
Car.prototype = {
	lang: 5,
	width: 2.5
}
var car = new Car();
console.log('width' in car);

Untitled

⭐️ A instanceof B

判断左边的A是否是通过右边的B构造出来

function Car() {}
var car = new Car();

function Person() {}
var p = new Person();

function Student() {}
Student.prototype = p;
var stu = new Student();

console.log(car instanceof Car);
console.log(p instanceof Car);
console.log([] instanceof Array);
console.log(car instanceof Object);
console.log([] instanceof Object);
console.log({} instanceof Object);

console.log(stu instanceof p);

Untitled

几种判断类型的方式

var a = [];
console.log(a.constructor === Array);
console.log(a instanceof Array);
var str = Object.prototype.toString.call(a);
console.log(str == '[object Array]');