导航


HTML

CSS

JavaScript

浏览器 & 网络

版本管理

框架

构建工具

TypeScript

性能优化

软实力

算法

UI、组件库

Node

冷门技能

⭐️ 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]');

Untitled

⭐️ 推荐的判断变量的数据类型的方案

var a = [];
if (Object.prototype.toString.call(a) === "[object Array]") {
  console.log("是 Array 构造函数创建");
} else {
	console.log("不是 Array 构造函数创建")
}

Object.prototype.toString.call

原理:

var str = Object.prototype.toString.call(a);
console.log(str);
Object.prototype = {
	toString: function() {
  	this.toString(); // call改变this指向 -->> a.toString()
  }
}