js的数据类型有 Number String Undefined Null Boolean Symbol Bigint Object。Object 有 Funtion Array 等。
js中的所有对象 A 都有一个 __proto__ ,或者叫 [[prototype]] 属性,这个属性指向了某个对象 B, 当查找 A 上的属性找不到的时候,就会去 B 上查找,然后一层层向上查找,直到 Object.prototype 为止,像是一个查找的链条,称之为原型链。
请考虑如下面试题目:
// https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Data_structures
let obj1 = {}
let obj2 = function(){}
let obj3 = new obj2() // obj3 是个对象
// 查找路线
// obj1 -> Object.prototype
// obj3 -> Object.prototype
// obj2 -> Function.prototype -> Object.prototype
console.log(obj1.__proto__ === Object.prototype) // true
console.log(obj2.__proto__ === Function.prototype) // true
console.log(Object.__proto__ === Object.prototype) // false
console.log(Object.__proto__ === Function.prototype) // true
console.log(Function.__proto__ === Function.prototype) // true
console.log(Function.prototype.__proto__ === Object.prototype) // true
console.log(Object.prototype.isPrototypeOf(Function.prototype)) // true
// Function.prototype 的原型指向 Object.prototype
var foo = function () {}
Object.prototype.a = 1
Function.prototype.b = 2
var bar = new foo()
/**
* bar 是得到的一个对象,所以bar.a 能找到 Object.prototype 去
*/
console.log(foo.a) // 1
console.log(foo.b) // 2
console.log(bar.a) // 1
console.log(bar.b) // undefined
# defineProperty 时 getter 和 value writable 不能并存
let c = {}
Object.defineProperty(c, 'x', {
// value: 1, // getter 和 value writable 不能并存
// writable: true, // getter 和 value writable 不能并存
get() {
return 1
}
})