JavaScript之判断对象是否存在指定字段、hasOwnProperty、call、hasOwn、params、Object、prototype


1、原始方法

let obj = {
    
    
	id: 7,
	name: 'function',
	fn: function () {
    
    
		return this.id;
	}, 
	test: function test(params) {
    
    
		// 旧的判断方法
		return Object.prototype.hasOwnProperty.call(obj, params);
	}
};

console.log(obj.test('fn'));
// true
console.log(obj.test('a'));
// false
console.log(obj.fn());
// 7

2、新方法

let obj = {
    
    
	id: 7,
	name: 'function',
	fn: function () {
    
    
		return this.id;
	},
	test: function test(params) {
    
    
		// 新方法
		return Object.hasOwn(obj, params);
	}
};

console.log(obj.test('fn'));
// true
console.log(obj.test('a'));
// false
console.log(obj.fn());
// 7

猜你喜欢

转载自blog.csdn.net/weixin_51157081/article/details/125089171
今日推荐