mardi 16 février 2016

Defining Properties on a Javascript Object - Object.definedProperties displays empty object

I have been following javascript design patterns and was implementing ES5 properties using the code found at this location.

http://ift.tt/1mXQFIs

Test 1

Use a function to define 3 properties

  • Check the values are ok: SUCCESS
  • Log the object to see if the data looks ok: SUCCESS

Test 2

Use Object.definedProperties to define 3 properties

  • Check the values are ok: SUCCESS
  • Log the object to see if the data looks ok: FAIL

Test 1 Code

it('should construct object with some single properites added using helper function', function (done) {

  var person = Object.create(Object.prototype);

  // Populate the object with properties
  pattern.defineProp(person, "car", "Delorean");
  pattern.defineProp(person, "dateOfBirth", "1981");
  pattern.defineProp(person, "hasBeard", false);

  console.log(person.car);
  console.log(person);
  console.log(typeof person);
  console.log(JSON.stringify(person));

  person.car.should.equal('Delorean');
  person.dateOfBirth.should.equal('1981');
  person.hasBeard.should.equal(false);

  // Produces
  // Delorean
  // { car: 'Delorean', dateOfBirth: '1981', hasBeard: false }
  // object
  // {"car":"Delorean","dateOfBirth":"1981","hasBeard":false}

  done();
});

Test 2 Code

it('should construct object with multiple properties using standard ES5 syntax', function (done) {

  var person = Object.create(Object.prototype);

  // Populate the object with properties
  Object.defineProperties(person, {

    "car": {
      value: "Delorean",
      writable: true
    },
    "dateOfBirth": {
      value: "1981",
      writable: true
    },
    "hasBeard": {
      value: false,
      writable: true
    }

  });
  console.log(person.car);
  console.log(person);
  console.log(typeof person);
  console.log(JSON.stringify(person));

  person.car.should.equal('Delorean');
  person.dateOfBirth.should.equal('1981');
  person.hasBeard.should.equal(false);

  // Produces
  // Delorean
  // {}
  // object
  // {}

  done();
});

Define Prop Function

exports.defineProp = function ( obj, key, value ){
  var config = {
    value: value,
    writable: true,
    enumerable: true,
    configurable: true
  };
  Object.defineProperty( obj, key, config );
};

Output

Aucun commentaire:

Enregistrer un commentaire