Estoy tratando de escribir un método genérico para poder probar la igualdad de dos variables, por ejemplo:
function shallow_equals(x, y) { let same_type = typeof x === typeof y, is_object = typeof x === 'object'; if (!same_type) return false; if (same_type && !is_object) return x === y; // treat it as an object if (Object.keys(x).length !== Object.keys(y).length) return false; for (key of Object.keys(x)) { if (x[key] !== y[key]) { return false; } } return true; } // shallow comparison of two objects Object.prototype.equals = function(other) { console.log('self ==>', this); console.log('other ==>', other); console.log('shallow equal?', shallow_equals(this, other)); } let z = 4; let w = 4; z.equals(w);Tengo curiosidad por qué lo anterior no funciona, ya que los dos tipos que recibe son:
[Number: 4] --> object 4 --> number¿Por qué ocurre esto y cuál sería la forma correcta de tener una función como esta?