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.prototype
即Programmer.prototype.__proto__
example.__proto__.__proto__.__proto__===Object.prototype
所有對象都是Object的實例,並繼承Object.prototype的屬性和方法。
原型鏈
找一個屬性,首先在example.__proto__
去找,如果沒有,再去example.__proto__.__proto__
找,……,再到Object.prototype
,一直到null
,即Object.prototype.__proto__ === null
。這個串起來的鏈就是原型鏈。
比如:example.code
、example.work
、example.doSth
、example.toString
都有,而example.foo
就爲undefined
。