[js]面向对象1
数据赋值拷贝
1,值得赋值是独立的
num1=12;
num1=num2
将存储值赋值一份存储.
2,
var age=22;
age2=age;
age=24
console.log(age);
age2依旧是22
引用类型的赋值共享数据
指向同一片内存
3,对象的赋值
var p={
name:"shizi",
age:22,
}
p1=p;
console.log(p.name,p.age);
console.log(p1.name,p1.age);
console.log("------------------------");
p.name="maotai";
p.age=24;
console.log(p.name,p.age);
console.log(p1.name,p1.age);
值类型赋值--函数形参&实参
var num = 10;
function foo(num){
num=100;
console.log(num);
}
console.log(num);
#10
var num = 10;
function foo(num1){
//实参: 调用时传递的参数
//形参: 定义时传递的参数
num1=100;
console.log(num1);
}
foo(num);
console.log(num);
# 10 100 10
var num = 10;
function foo(num1){
//实参: 调用时传递的参数
//形参: 定义时传递的参数
//var num1=num;
num1=100;
console.log(num1);
}
foo(num);
console.log(num);
# 10 100 10
引用类型赋值
1
var obj={
name:"宅男"
}
function jinhua(param){
param.name="高富帅";
}
jinhua(obj);
console.log(obj.name);
#高富刷
2
var obj={
name:"宅男"
}
function jinhua(param){
param.name="高富帅";
//重新开辟内存,param重新指向一片mem
param={
name: "腐女"
}
param.name="宅男";
}
jinhua(obj);
console.log(obj.name);
#宅男
对象的动态性
动态添加属性和方法
p={
name:"刘德华",
age:22
}
//添加属性方式1
p.gender="male";
//添加属性方式2
p["salary"]=2000;
//添加对象类型属性
p.foo=function(){console.log("sing");}
//访问属性方式1
console.log(p.foo());
console.log(p.salary);
//访问属性方式2
console.log(p["name"];
p={
name:"刘德华",
age:22
}
p["salary"]=2000; //是字符串
console.log(p.salary);
p={
name:"刘德华",
age:22
}
p[0]=2000; //隐式将0转换为字符串
//console.log(p.0); //发现这种方式访问报错
console.log(p["0"]); //这种方式正常访问
以下等价
p={
name:"刘德华",
age:22
}
p[{}]="shizi";
console.log(p);
p={
name:"刘德华",
age:22
}
p["[object Object]"]="shizi";
console.log(p);
探究
a={}
console.log(a.toString());
#"[object Object]"