几个公式
-
对象.__proto__ === 构造函数.prototype。
- 由此可以延伸出 函数名.__proto__ === Function.prototype。
function Foo(){} var f = new Foo() alert(f.__proto__ === Foo.prototype) alert(Foo.__proto__ === Function.prototype)
-
默认时,构造函数.prototype.constructor === 构造函数 ==== 原型.constructor:
function Foo(){} alert(Foo.prototype.constructor === Foo)
常用方法
-
hasOwnProperty():判断对象是否拥有指定的属性—— 这个属性不能是从原型继承过来的。
function Demo () { } var d = new Demo() alert(Demo.constructor) alert(Demo.hasOwnProperty('constructor')) // false Demo.age = '1341' alert(Demo.hasOwnProperty('age')) // true
调用 Demo.constructor 是有值输出的,但 hasOwnProperty 返回 false,因为 constructor 属性是 Demo 从其原型继承过来的。
随后为 Demo 对象定义了 age 属性,所以最后一句输出的是 true。 -
isPrototypeOf:判断调用者是不是参数的原型。、
function Demo () { } var p = {}; Demo.prototype = p; alert(p.isPrototypeOf(new Demo())); // true alert(p.isPrototypeOf(new Array())); // false
由于 Object.prototype 是原型链的最顶层,所以但凡 Object.prototype 作为调用者时,结果永远为 true。
-
in 操作符:判断对象中是否有指定的属性,无论该属性是在原型中还是在构造函数中
function Demo(){ } Demo.prototype.age = 1231 var d = new Demo() alert('age' in d) // true
网友评论