对象、原型与原型链

Object.defineProperty
let obj = {
    key0: 0
}
Object.defineProperty(obj, "key1", {
    value: "1",
    writable: false, // 是否可写,默认false。obj.key1="1.0"; 不可写,不起作用
    configurable: false, // 是否可以再次配置,默认false。不能再设置value,writable,configurable等属性
    enumerable: false // 是否可枚举,默认false。不能在(for...in)中遍历
})
console.log(Object.getOwnPropertyDescriptor(obj, "key0")); // {value: 0, writable: true, enumerable: true, configurable: true}
console.log(Object.getOwnPropertyDescriptor(obj, "key1")); // {value: "1", writable: false, enumerable: false, configurable: false}
判断对象是否有指定属性或方法而不是继承的

obj.hasOwnProperty("toString")

获取对象属性的数组
Object.getOwnPropertyNames(obj)

Object.keys(obj) // 获取不到不可枚举(enumerable: false)的属性
Object.assign

assign() 用于将所有可枚举属性的值从一个或多个源对象复制到目标对象。同 $.extend();

Object.assign({}, obj); // {key0: "0"}
$.extend({}, obj); // {key0: "0"}
对象和JSON的转化
let xmObj = {
    name: "xiaoming",
    age: 20,
    sex: "男",
    isMarry: false
}
// 序列化成JSON
var res = JSON.stringify(xmObj, null, '  '); // typeof res == "string"
// 解析成对象
var resO = JSON.parse(res); // typeof resO == "object"
先看一段代码
function Person(name, age){
    this.name = name;
    this.age = age;
}
Person.prototype.work=function(){}

function Programmer(name,age){
    Person.call(this,name,age);
}
Programmer.prototype = new Person();
Programmer.prototype.code=function(){}; // 如果写成对象会覆盖继承来的属性和方法,即赋值为{...}。

let example = new Programmer('码农',24); // 创建实例,example是实例,Programmer是原型。

Object.prototype.sth = function(){}
new的过程:创建一个空对象,让this指向它,通过this.name,this.age等赋值,最终返回this。
原型和实例

在上面代码中,Programmer是原型,example是它的实例。用instanceof检测,有
example instanceof Programmer === true
example instanceof Person === true
example instanceof Object === true

通过example.constructor属性返回对创建此对象的数组函数的引用。
example.constructor===Person
example.constructor===Person.prototype.constructor
但是constructor 属性易变,不可信赖,它可以通过修改prototype而手动修改。

实例的__proto__对应原型的prototype
example.__proto__===Programmer.prototype
example.__proto__.__proto__===Person.prototypeProgrammer.prototype.__proto__
example.__proto__.__proto__.__proto__===Object.prototype
所有对象都是Object的实例,并继承Object.prototype的属性和方法。

原型链

找一个属性,首先在example.__proto__去找,如果没有,再去example.__proto__.__proto__找,……,再到Object.prototype,一直到null,即Object.prototype.__proto__ === null。这个串起来的链就是原型链。
比如:example.codeexample.workexample.doSthexample.toString都有,而example.foo就为undefined

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章