Prototypes - Overriding Prototypal Methods


var x = 4;
var y = "4";

x.valueOf(); // returns 4
y.valueOf(); // returns "4"

x.valueOf() == y.valueOf(); // returns true (although its not)

x.valueOf() === y.valueOf(); // returns false
// triple equals will not ignore type


var a = [3,"blind","mice"];
a.valueOf(); // returns [3,"blind","mice"]

var b = new Number(6);
b.valueOf(); // returns 6

// what happens when we call vlaueOf on an object that we have created?

var Tornado = function(category,affectedAreas,windGust){
    this.category = category;
    this.affectedAreas = affectedAreas;
    this.windGust = windGust;
}

var cities = [["Kansas City",464310],["Topeka",127939],["Lenexa",49398]];
var twister = new Tornado("F5",cities,220);

twister.valueOf(); // returns Tornedo {category:"F5",location: Array[3],windGust:220}
// the valueOf fucntion for custom Objects just defaults to a list of their properties
// just like logging them out
console.log(twister.valueOf());


Tornado.prototype.valueOf = function(){
    var sum = 0;
    for(var i = 0; i < this.affectedAreas.length; i++){
        sum += this.affectedAreas[i][1];
    }
    return sum;
};

console.log(twister.valueOf());

// overriding toString();

var x = 4;
var y = "4";

x.toString(); // returns "4"
y.toString(); // returns "4"

var a = [3,"blind","mice"];
a.valueOf(); // returns "3,blind,mice";


Tornado.prototype.toString = function(){
    var list = "";
    for(var i = 0; i < this.affectedAreas.length; i++){
        if(i < this.affectedAreas.length - 1){
            list = list + this.affectedAreas[i][0] + ", ";
        }else{
            list = list + "and " + this.affectedAreas[i][0];
        }
    }
    return "This tornedo has been classified as an " + this.category +
        ", with wind gusts up to " + this.windGust + "mph. Affected areas are: " +
        list + ", postentially affecting a population of " + this.valueOf() + ".";
};

console.log(twister.toString());

// finding an Object's constructor and its prototype

// outputs constrtor
twister.constructor;
console.log(twister.constructor);

// outputs constructors overriding prototypes
twister.constructor.prototype;
console.log(twister.constructor.prototype);

// which is the same as

twister.__proto__;
console.log(twister.__proto__);

// hasOwnProperty();

cities.push(["Olathe",130045]);

Object.prototype.findOwnerOfProperty = function(propname){
    var currentObject = this;
    while(currentObject != null){
        if(currentObject.hasOwnProperty(propname)){
            return currentObject;
        }else{
            currentObject = currentObject.__proto__;
        }
    }
    return "No property found!";

};

twister.findOwnerOfProperty("valueOf");
console.log(twister.findOwnerOfProperty("valueOf"));

twister.findOwnerOfProperty("goToOz");
console.log(twister.findOwnerOfProperty("goToOz"));
By Chris Armstrong
Sunday 9th March 2014

Comments

There are currently no comments

Make a comment