javascript关于使用prototype给对象添加函数
来源:互联网 发布:mac英雄联盟美服网站 编辑:程序博客网 时间:2024/06/06 09:01
首先,常见的为对象添加函数的代码如下:
function Person(){this.name="ljx"; this.age=20;this.show=function(){document.write("我的名字是:"+this.name);}} var p1=new Person();var p2=new Person();document.write(p1.show==p2.show); //false 说明两个对象的函数都各自占用一份内存 等号判断的是地址(对象函数的地址)
使用prototype给对象添加函数的代码如下:
function Person(){this.name="ljx"; this.age=20;} function display(){document.write("我的名字是:"+this.name);}Person.prototype.show=display;var p1=new Person();var p2=new Person();document.write(p1.show==p2.show);//true 此时这个函数使共享的,仅暂用一份内存
注明:如果等号两边是对象或者对象的函数,则比较地址是否相等(即判断两者是否引用的同一对象)
所以,我觉得第二个方法给对象添加函数比第一个好
特别说明:使用prototype添加的函数,不能调用私有变量和函数
function Person(name1,age1){this.name=name1;var age=age1;}Person.prototype.show=function(){document.write("名字:"+this.name); //这样是没问题的}var p3=new Person('ljx',20);p3.show();//若把上面代码改为如下,则报错Person.prototype.show=function(){document.write("名字:"+this.name+" 年龄:"+this.age); //这样是错误的 }var p3=new Person('ljx',20);p3.show(); //age输出undefined
0 0
- javascript关于使用prototype给对象添加函数
- Javascript prototype属性使用(给内置对象添加新的方法,方便调用)
- 通过 prototype 为 JavaScript 的 String 对象添加方法(函数)
- 给对象添加属性----Prototype原型对象
- 关于给javascript对象添加、删除、修改对象的属性
- 22-JavaScript-面向对象-构造函数-prototype
- JavaScript中prototype(原型)给字符串对象添加一个toCharArray的方法,reverse(翻转)的 方法
- JavaScript对象添加行为,使用构造函数创建对象
- 【javascript】使用prototype属性格式化Date对象
- javascript使用原型(prototype)方法创建对象
- javascript的prototype给对象增加方法属性
- 用prototype给JS中的String对象追加函数
- JavaScript: 给 Date 对象添加格式化方法
- javascript快速给对象添加属性
- 如何给JavaScript添加一个自定义对象
- javascript给builtin对象添加新方法
- JavaScript 如何给对象添加方法
- 【javascript笔记】关于函数的构造函数和prototype<四>
- Centos网站服务器使用DropBox定时备份方案
- spring框架学习(五)注解
- Nginx + Lua + GraphicsMagick 实现切图服务
- JavaScript复习--点击显示登陆窗口(层)
- table的数据行tr上下移动
- javascript关于使用prototype给对象添加函数
- 快速排序
- 滤波器设计指标
- JSP 中 application,cookie,session 的区别
- GNU ARM汇编语法
- 【C++】关于指针函数
- 暴力法求解——简单枚举(除法)
- wp开发:Button按下后空白背景改变
- $.ajax async