Object.prototype.forIn

by langdonx

JavaScript

Object.prototype.forIn = function(cb) {
  var key;

  for (key in this) {
    if (this.hasOwnProperty(key) === true) {
      cb.call(this, key, this[key]);
    }
  }
};

//Object.prototype.forIn = function(callback) {
//	Object.keys(this).forEach(function(key) {
//		callback.call(this, key, this[key]);
//	}.bind(this));
//};

// ~

function Thing() {
  this.a = true;
  this.b = false;
}

Thing.prototype.doStuff = function() {};

var o1 = {
    a: true,
    b: false
  },
  o2 = new Thing();

console.log('o1');
o1.forIn(function(key, value) {
  console.log('this:', this, 'key:', key, 'value:', value)
});

console.log('o2');
o2.forIn(function(key, value) {
  console.log('this:', this, 'key:', key, 'value:', value)
});