一、关于Object.defineProerty
Object.defineProperty(person, 'name',{
configurable:false, // 是否可以通过delete删除person的name的属性
value:undefined, // name的默认值
enumerable:true,// 能否通过for-in循环属性
get:function () {
return this.name
},
set:function (val) {
return this.name = val
}
})
二、创建对象
1.工厂模式
let createObj = (name, age, job) =>{
const obj = new Object()
obj.name = name
obj.age = age
obj.job = job
return obj
}
2.构造函数模式
function Person (name, age){
this.name = name
this.job = job
}
let person1 = new Person ('小明',15)
(1) constructor(构造函数)
perosn1.constructor === person //true
(2) instanceof
person1 instanceof Object // true
person1 instanceof Person // true
3.原型模式
function Person () {
}
Person.prototype.name = '小明'
Person.prototype.age = 15
Person.sayName = () =>{
console.log(this.name)
}
let person1 = new Person()
console.log(perosn1.name) // 小明
(1)isPrototyoeOf(构造函数和new 对象的关系)
console.log(Person.prototype.isPrototypeof(person1)) // 构造函数Person的原型是person1的‘原型’ true
(2)Object.getPrototypeOf(构造函数和new 对象的关系)
console.log(Object.getPrototyoeOf(perosn1) == Person.prototype) // true
(3)delete 只能删除来自实例的属性,实例的属性优先级高于原型中的属性值
function Person () {}
Person.prototype.name = 'xxx'
let person1 = new Person()
peron1.name = '小明'
console.log(person1.name) // 小明
delete peron1.name
console.log(person1.name) // xxxx
(4)hasOwnProperty() 与 in判断属性是在实例上还是在原型上
function isInPrototype (Object, name) {
return !Object.hasOwnProperty(name) && (name in Object)
}
// Object.hasOwnProperty('name')只要对象含name属性都为true
// 'name' in Object 只有当name属性在原型上时才会返回true
(5)原型的动态性
function Person () {}
var person1 = new Person()
Person.prototype.name = '小明'
console.log(person1.name) //undefined
4.构造函数与原型模式结合(待续20180808)