//初始化变量
var target = {}
//下面这段可以屏蔽
Object.defineProperties(target, {
sex: {
value: '男'
},
})
//对Object对象进行扩展方法
Object.prototype.setObjectAttrbute = function(key,value){
console.log('有人来设置你了,值为:' + value)
return this[key] = value
}
//再封装一层
Object.prototype.setAge = function(value){
return this.setObjectAttrbute("age",value)
}
//查看修改前属性
console.log(target.age)
//执行方法,两种方法结果一样
console.log(target.setObjectAttrbute("age",99))
console.log(target.setAge(99))
//查看新的target
console.log(target)
</script>
对象合并:
var obj = {a:1, name: 'test'}var shuxing = {name:"super",sex:"19",work:"IT"}
for(var r in shuxing){
eval("obj."+r+"=shuxing."+r)
}
alert(obj.a)
alert(obj.name)
alert(obj.sex)
alert(obj.work)
当然可以写成函数方式:
function objMerger(obj1, obj2){
for(var r in obj2){
eval("obj1."+r+"=obj2."+r)
}
return obj1
}
obj = objMerger(obj, shuxing)
function sortNumber(a,b){
return a.number - b.number//按印数排名
}
function element(name,number){//name为书名,number是什么印数
this.name=name
this.number=number
this.toString=function(){//关键要重写toString,返回书名
return this.name
}
}
var arr = new Array(3)
arr[0] = new element("x",2000)
arr[1] = new element("y",1000)
arr[2] = new element("z",3000)
document.write(arr.sort(sortNumber))