对象之成员函数:
对象不仅只有属性,还要有行为(函数)
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script language="JavaScript" type="text/javascript"> function Person(name, age) { //传递实参初始化属性 this.name = name; this.age = age; // 这就是一个公开的函数,这样的话浪费资源 this.show = function() { document.write("名字=" + this.name + " " + "年龄=" + this.age + "<br/>"); } this.add = function() { var res = 0; for(var i = 1; i <= 1000; i++) { res += i; } return res; } } var p1 = new Person("宋江", 90); p1.show(); var p2 = new Person("李逵", 78); p2.show(); document.write("res=" + p1.add()); </script> </head> <body> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script language="JavaScript" type="text/javascript"> function Person(name, age) { //传递实参初始化属性 this.name = name; this.age = age; // 这就是一个公开的函数,这样的话浪费资源 this.add = function() { var res = 0; for(var i = 1; i <= 1000; i++) { res += i; } return res; } } function show(){ document.write("名字=" + this.name + " " + "年龄=" + this.age + "<br/>"); } var p1 = new Person("宋江", 90); //函数功能传递 p1.abc=show; p1.abc(); //调用二 p1.bcd=function show1(){ document.write("名字"+this.name); } p1.bcd(); </script> </head> <body> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script language="JavaScript" type="text/javascript"> function Person(){ this.name="abc"; this.age=900; this.abc=function(v1,v2){ document.write(this.name+" "+this.age+" "+v1+" "+v2+"<br/>"); } } var p1=new Person(); p1.abc(); p1.abc("背景","天津"); var p2=new Person(); p2.abc(); p2.abc("南京","东京"); </script> </head> <body> </body> </html>
使用prototype去绑定一个函数给shout,直接绑定给类,不需要创建对象时创建新的函数属性
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script language="JavaScript" type="text/javascript"> function dog() {} var dog1 = new dog(); dog.prototype.shout = function() { document.write("小狗" + "<br/>"); } dog1.shout(); var dog2 = new dog(); dog2.shout(); //判定是否为同一个函数 document.write(dog1.shout == dog2.shout); </script> </head> <body> </body> </html>
通过==符号可以判断地址是否相等
原文:https://www.cnblogs.com/helloworld2019/p/10930137.html