zoukankan      html  css  js  c++  java
  • [Javascript] Prototype, hasOwnProperty(), valueOf() and toString() methods.

    Sometime, use can rewrite the toString , valueOf method to make those function more useful:

    For exmaple, we can make valueOf() function to calcualte the sum, and then use toString method to display the information of the object we create.

    var Tornado = function(category, affectedAreas, windGust){
        this.category = category;
        this.affectedAreas = affectedAreas;
        this.windGust = windGust;
    };
    
    var cities = [["Kansas City", 46310],["Topeka", 127939],["Lenexa", 49398]];
    var twister = new Tornado("F5", cities, 220);
    cities.push(["Olathe", 130045]);
    twister.toString();
    
    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 tornado has been classified as an " + this.category+
        ", with wind gusts up to "+ this.windGust+ "mph. Affected areas are:"+
        list+", potentially affecting a population of "+ this.valueOf() + ".";
    };
    
    Tornado.prototype.valueOf = function(){
    
        var sum = 0;
        for(var i = 0; i < this.affectedAreas.length; i++){
            sum += this.affectedAreas[i][1];
        }
        return sum;
    }
    
    Object.prototype.findOwnProperty = function(propName){
        var currentObject = this;
        while(currentObject !== null){
            if(currentObject.hasOwnProperty(propName)){
                return currentObject;
            }else{
                currentObject = currentObject.__proto__;
            }
        }
        return "No property found!";
    }
    twister.findOwnProperty("valueOf");
  • 相关阅读:
    托管代码和非托管代码效率的对比
    托管程序与非托管程序的区别
    第15章 C# ADO.NET数据库操作
    第14章 C#进程与线程
    第13章 C#异常与调试
    第12章 C# WinForm
    第11章 C#委托和事件
    第10章 C#文件操作
    第9章 C#泛型
    第8章 C#集合
  • 原文地址:https://www.cnblogs.com/Answer1215/p/3903806.html
Copyright © 2011-2022 走看看