__proto__ or prototype ?

Reading time ~1 minute

  function foo(x,y) {
    this.x = x;
    this.y = y;
  };

  var bar = new foo;

  bar.__proto__ === foo.prototype // true
  bar.__proto__.proto__ === Object.prototype //true

  foo.__proto__ === Function.prototype //true
  foo.__proto__.__proto__ === Object.prototype // true
  bar instanceof foo
  foo instanceof Function
  bar instanceof Object

Create a function neww, so that it works like the new operator:

  function neww(constructor, args) {
    // ..
  }

  function Person(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  Person.prototype.greeting = function() {
    console.log('Hello, ' + this.firstName + ' ' + this.lastName);
  }

  var john = neww(Person, ['John', 'Doe']);
  john.greeting();          // Hello, John Doe
  john.constructor;         // Person(firstName, lastName) {...}

Hint: You may want to go back to the “Constructors and Prototypes” topic and review when a function is called as a constructor, what effectively happens. Note that if the constructor function has no explicit return, the created object will be returned.

solution:

  function neww(constructor, args) {
    var object = Object.create(constructor.prototype);
    var result = constructor.apply(object, args);

    object.constructor = constructor;
    return result === undefined ? object : result;
  }

Discussion:

https://launchschool.com/posts/82d9af2a

Kevin: You have to think about what happens when you use the new keyword to create an object from a constructor function:

assuming the return value is obj, then:

  • obj’s constructor property need to point to the constructor function
  • obj’s proto_ property needs to point to construction function’s prototype
  • the constructor function needs to be called with obj as its context to mutate the obj object.

I feel your solution would satisfy the second requirement, but wouldn’t satisfy the first and third requirements.

  function neww(constructor, args) {
    var obj = {};

    // 1. obj's constructor property need to point to the constructor function
    obj.constructor = constructor;
    // 2. obj's __proto__ property needs to point to construction function's prototype
    obj.__proto__ = constructor.prototype;
    // 3. the constructor function needs to be called with obj as its context to mutate the obj object.
    constructor.apply(obj, args);

    return obj;
  }

to_param in Ruby on Rails

If I want a custom slug=======================I walk through this cutstom slug.1. create migration `add_slug` to add a column inside the...… Continue reading

What is ORM in Rails mean?

Published on July 14, 2017