浅拷贝
- for-in(遍历一个实例对象,原型上的属性也会打印)
Object.prototype.num = 1
function shallowClone(origin, target) {for (var key in origin) {target[key] = origin[key]}
}
var p1 = {name: '人类',daughter: {first: 'Jessica',}
}
var p2 = {}
shallowClone(p1, p2)
p2.daughter.second = 'Krystal'
console.log(p1, p2)
- 用hasOwnProperty剔除原型上的属性
Object.prototype.num = 1
function shallowClone(origin, target) {var tar = target || {}for (var key in origin) {if (origin.hasOwnProperty(key)) {tar[key] = origin[key]}}return tar
}
var p1 = {name: '人类',daughter: {first: 'Jessica',}
}
var p2 = shallowClone(p1)
p2.daughter.second = 'Krystal'
console.log(p1, p2)
深拷贝
- 我的实现方式(未考虑正则、方法、Date)
var baseType = ['[object String]', '[object Null]', '[object Undefined]', '[object Boolean]', '[object Number]']
Object.prototype.num = 1
function isBaseType(target) {return baseType.includes(Object.prototype.toString.call(target))
}
function deepClone(origin, target) {var tar = target ? target : Array.isArray(origin) ? [] : {} // 关键语句for (var key in origin) {if (isBaseType(origin[key]) && origin.hasOwnProperty(key)) {tar[key] = origin[key]} else if (!isBaseType(origin[key])) {tar[key] = deepClone(origin[key], tar[key]) // 关键语句}}return tar
}
var p1 = {name: '人类',daughter: {first: 'Jessica',grandSon: [12, 15]}
}
var p2 = deepClone(p1)
p2.daughter.second = 'Krystal'
p2.daughter.grandSon.pop()
console.log(p1, p2)
- JSON (不能拷贝正则、方法…)
var p1 = {name: '人类',daughter: {first: 'Jessica',grandSon: [12, 15],fun: function () { }}
}
var str = JSON.stringify(p1)
var p2 = JSON.parse(str)
console.log('p1', p1)
console.log('str', str)p2.daughter.second = 'Krystal'
p2.daughter.grandSon.pop()
console.log('p2', p2)
练习
注意
注意
function Foo() {getName = function () { // 没经过var 会被提升到全局console.log(1)}return this
}
Foo.getName = function () {console.log(2)
}
Foo.prototype.getName = function () {console.log(3)
}
var getName = function () {console.log(4)
}
function getName() {console.log(5)
}
Foo.getName() // 函数也是对象,增加属性 2
getName() // 4 变量声明提升 函数声明 变量赋值
Foo().getName() // 1 没有new
getName() // 1
new Foo.getName()// 2 (new 2,.运算符优先级高于new)
new Foo().getName()// 3
new new Foo().getName()// 3
GO = {getName:undefined(变量声明)- fn(函数声明) - 新fn(变量赋值)- 新fn
}
- 判断闰年(整除4&&不能整除100 || 整除400)