夺命雷公狗---javascript NO:24 对象之间的赋值操作
1、把对象做为参数进行传递
例1:函数形参值的改变不会影响实参,但是对象除外
1)普通传值
<!DOCTYPE html> <html> <head> <meta charset=’utf-8′> <title></title> </head> <body> <script> function display(name){ name = ‘lisi'; } var name = ‘zhangsan'; display(name); alert(name); //输出zhangsan </script> </body> </html>
2)引用传值(object)
<!DOCTYPE html> <html> <head> <meta charset=’utf-8′> <title></title> </head> <body> <script> function display(obj){ alert(obj.name+’-‘+obj.age); obj.name = ‘zhangsan'; } //定义一个自定义类 function Person(){} var p1 = new Person(); p1.name = ‘lisi'; p1.age = 22; display(p1); //lisi-22 alert(p1.name); //zhangsan </script> </body> </html>
2、把一个对象做为函数的返回值,返回更多的数据
<!DOCTYPE html> <html> <head> <meta charset=’utf-8′> <title></title> </head> <body> <script> function display(name,age){ var obj = new Object(); obj.name = ‘zhangsan'; obj.age = 22; obj.address = ‘广东省广州市'; return obj; } var p1 = display(); alert(p1.name+p1.age+p1.address); </script> </body> </html>
3、实际应用:返回两个数的四则运算
示例:
<!DOCTYPE html> <html> <head> <meta charset=’utf-8′> <title></title> </head> <body> <script> function display(yi,er){ //定义一个对象 var counter = new Object(); counter.jia = yi + er; counter.jian = yi – er; counter.cheng = yi * er; counter.chu = yi / er; return counter; } var obj = display(100,20); alert(obj.jia+’—‘+obj.jian+’—‘+obj.cheng+’—‘+obj.chu); </script> </body> </html>