paint-brush
[ Javascript ] Cracking nuts, override Object.constructor( )by@peterchang_82818
9,767 reads
9,767 reads

[ Javascript ] Cracking nuts, override Object.constructor( )

by December 6th, 2016
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

<strong>This is an example from </strong><a href="http://stackoverflow.com/questions/9267157/why-is-it-impossible-to-change-constructor-function-from-prototype" target="_blank"><strong><em>stackoverflow</em></strong></a><strong><em>:</em></strong>

Company Mentioned

Mention Thumbnail
featured image - [ Javascript ] Cracking nuts, override Object.constructor( )
 HackerNoon profile picture

unsplash.com

I like javascript, as always. But it was hurt, every time when I was required to program in OOP pattern. All those topics: Objects, Classes,Prototype, Inheritance etc., are the pain for developer, which caused by the personality of “loose comparison temper” and “auto type conversion OCD” of JS.

This is an example from stackoverflow:

First, Rabbit is a object, with public valuable jumps and default value “yes”.

function Rabbit() {    this.jumps = "yes";};var rabbit = new Rabbit();console.log(rabbit.jumps);                    // yesconsole.log(Rabbit.prototype.constructor);    // outputs exactly the code of the function Rabbit();

Second, we want to change the code in Rabbit() so that the var jumps with different default value “no”. Well, modifying default value of Object, and there is Object.prototype.constructor( ), my gut tells me modifying the constructor function and problem will solved. BUT it is not.

Rabbit.prototype.constructor = function Rabbit() {    this.jumps = "no";};console.log(Rabbit.prototype.constructor);    // again outputs the code with new this.jumps = "no";var rabbit2 = new Rabbit();// create new object with new constructorconsole.log(rabbit2.jumps);                   // still 

What is happening is that Rabbit.prototype.constructor is just a pointer to the original constructor (function Rabit(){…}), so that users of the ‘class’ can detect the constructor from an instance.

By Juan

If you want to redefine a constructor, just do

var oldProto = Rabbit.prototype;Rabbit = function() {   this.jumps = "no";};

Rabbit.prototype = oldProto;

You also like Cracking nuts series:


[Expressjs] override res.send[Expressjs] put the IP to BlackList

Like this story? It is helpful to others? It helps me know if you’d like to see write more about his topic and helps people see the story, when tap the heart below.

Reference:


_Why is it impossible to change constructor function from prototype?_http://js-bits.blogspot.tw/2010/08/javascript-inheritance-done-right.html


_Tuesday, August 17, 2010 Javascript Inheritance Done Right_http://stackoverflow.com/questions/9267157/why-is-it-impossible-to-change-constructor-function-from-prototype