博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Javascript] Prototype, hasOwnProperty(), valueOf() and toString() methods.
阅读量:4978 次
发布时间:2019-06-12

本文共 1661 字,大约阅读时间需要 5 分钟。

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");

 

转载于:https://www.cnblogs.com/Answer1215/p/3903806.html

你可能感兴趣的文章
编译预处理指令:文件包含指令、宏定义指令、条件编译指令
查看>>
PHP函数 ------ ctype_alnum
查看>>
网站安全
查看>>
WS-Addressing 初探
查看>>
.NET+模块编排+数据库操作类的封装+分层架构+实体类+Ajax.net+Athem.NET+javascript+Activex组件+用户权限等...
查看>>
Markdown不常见功能
查看>>
(二)NUnit单元测试心得
查看>>
hdu_2604Queuing(快速幂矩阵)
查看>>
frame.bounds和center
查看>>
HDU 1102 Constructing Roads
查看>>
android StaticLayout参数解释
查看>>
多线程之ThreadLocal类
查看>>
Qt-读取文本导出word
查看>>
OC语言description方法和sel
查看>>
C#中得到程序当前工作目录和执行目录的五种方法
查看>>
扫描线与悬线
查看>>
用队列和链表的方式解决约瑟夫问题
查看>>
python 迭代器与生成器
查看>>
[django]form的content-type(mime)
查看>>
仿面包旅行个人中心下拉顶部背景放大高斯模糊效果
查看>>