[Solved] How to get specific value of the object?


new myObj creates and returns a new object, even though you have return 7 in your function. The new operator is specifically for creating objects, and has the interesting behavior of completely ignoring the return value of the constructor function unless it’s a non-null object reference; instead, new returns the object it created. (If you do return a non-null object reference from the constructor function, it overrides new‘s default behavior; use cases for this are rare.)

If you just want to call the function and get its return value, don’t use new:

console.log(myObj());

If you want to create an object with a property on it, and set that property to 7, then print it, you need to create the property:

function myObj() {
    this.thePropertyName = 7;
}

…and then use it:

var o = new myObj();
console.log(o.thePropertyName);

…or:

console.log(new myObj().thePropertyName);

…but then you’re creating and releasing an object for no good reason.


Re your edit, which changes the question markedly:

this task:

new myObj() // return 1; new myObj() // return 2;

new myObj() + new myObj() = // return 7;

That’s a bizarre requirement. It breaks down like this:

  1. Every time you call new myObj, save a number (starting with 1).

  2. When the + operator is used on the objects, return that number.

You can do it, by using a common counter, a value on the instance, and overriding the default implementations of toString and valueOf; see comments in the code:

(function() {
  "use strict";

  // Use a scoping function to build `myObj` so that we
  // keep the counter private
  var myObj = (function() {
    // The counter
    var counter = 0;

    // The `myObj` function we'll return
    function myObj() {
      // Increment the counter, remember the number
      this.value = ++counter;
    }
    
    // When a coercion to number is preferred, JavaScript will
    // use the valueOf function
    myObj.prototype.valueOf = function() {
      return this.value;
    };
    
    // When a coercion to string is preferred, JavaScript will
    // use the toString function
    myObj.prototype.toString = function() {
      return String(this.value);
    };

    // Return `myObj` from our scoping function to export it
    return myObj;
  })();

  // Using it
  display(new myObj());               // "1"
  display(new myObj());               // "2"
  display(new myObj() + new myObj()); // 7

  // Utility function
  function display(msg) {
    var p = document.createElement("p");
    p.innerHTML = String(msg);
    document.body.appendChild(p);
  }
})();

6

solved How to get specific value of the object?