为对象添加原型
const obj = {
x:1,
y:2,
add:function(a, b){
return a + b
}
}
使用prototype添加原型
const Empty = function(){}
Empty.prototype \= obj
const empty \= new Empty()
empty.add(1, 2) // 3
使用Object.create()直接创建继承原型的对象的实例对象
const test = Object.create(obj, { // 第二个参数不传默认为{}
"a": {
value: 10,
writable:false
},
"b": {
value: 100
},
})
override重载时,不会修改原型本身
empty.x = 10
console.log(empty.x) // 10
console.log(obj.x) // 1
查看原型
Object.getPrototypeOf(empty)
检测属性
in和hasOwnProperty均可用来检测对象中属性是否存在
hasOwnProperty只能检测自有属性,无法查找原型链,in可以检测自有属性或继承属性
const o = {x:1}
o.hasOwnProperty("x")
"x" in o
getOwnPropertyDescriptor可查看当前属性描述,但只能查看自有属性
// 输出{ value: 1, writable: true, enumerable: true, configurable: true }
console.log(Object.getOwnPropertyDescriptor(o, "x"))
为对象添加属性
数据属性的四个特性分别是:值(value) 可写性(writable) 可枚举性(enumable) 可配置性(configurable)
Object.defineProperty(o, "y", {
value: "test", // 值
enumerable:false, // 是否可枚举
writable:false, // 可写性
configurable:false // 可配置性
})
存取器
存取器属性的四个特性分别是:读取(get) 写入(set) 可枚举性(enumable) 可配置性(configurable)
const o = {
x: "",
get getX(){
return this.x
},
set setX(val){
this.x = val
}
}
可以用闭包来实现私有属性,并定制get set
const Test = (function(){
let x \= "10"
return function(){
this.getX = function(){
return x
}
this.setX = function(val){
x \= val
}
}
})()
本文转自 https://www.cnblogs.com/xt112233/p/15613980.html,如有侵权,请联系删除。