请问以下代码中__proto__的使用是如何用意?
function ContextMenuHandler() {
this.showingEvents_ = new EventTracker();
}
ContextMenuHandler.prototype = {
__proto__: EventTarget.prototype,
/**
* The menu that we are currently showing.
* @type {cr.ui.Menu}
*/
menu_: null,
get menu() {
return this.menu_;
}
}
如果修改成以下有什么区别呢?
ContextMenuHandler.prototype = EventTarget.prototype;
prototype
属性一般用在构造函数上,构造函数创建的对象的__proto__
即为构造函数的prototype
var F = function(){}
F.prototype = {a:12}
var f = new F()
console.log(f.__proto__ === F.prototype)//true
设置如果改成下面那种代码,就不好给ContextMenuHandler.prototype
添加方法了,因为这样还会修改EventTarget.prototype
。其实也可以ContextMenuHandler.prototype = new EventTarget()
,但这样可能会继承不必要的属性。
__proto__
为一个对象实例具有的属性,指向一个原型对象prototype
为一个构造函数对象具有的属性,对象实例不具有这个属性,指向一个原型对象
当使用new操作符调用一个构造函数时,__proto__属性就被绑定到生成的实例对象上,指向这个构造函数的prototype属性指向的原型对象上。
函数也是对象
function EventTarget(){
}
EventTarget.prototype.getName=function(){
console.log("EventTarget.getName");
}
function ContextMenuHandler() {
this.showingEvents_=null;
}
ContextMenuHandler.prototype = {
__proto__: EventTarget.prototype,
menu_: null,
get menu() {
return this.menu_;
}
}
console.log(ContextMenuHandler.__proto__);//[native code]
console.log(typeof ContextMenuHandler.__proto__);//function 函数对象的原型是一个函数对象
console.log(ContextMenuHandler.prototype.__proto__===EventTarget.prototype);//true,原型对象的原型重新指向EventTarget.prototype指向的对象
var newContextMenuHandler=new ContextMenuHandler();
console.log(newContextMenuHandler.__proto__=== EventTarget.prototype);//false
console.log(newContextMenuHandler.__proto__=== ContextMenuHandler.prototype);//true
ContextMenuHandler.prototype = EventTarget.prototype;
var newContextMenuHandler2=new ContextMenuHandler();
console.log(newContextMenuHandler2.__proto__===EventTarget.prototype);//true
console.log(newContextMenuHandler2.__proto__=== ContextMenuHandler.prototype);//true
console.log(typeof ContextMenuHandler.__proto__);//function 函数对象的原型是一个函数对象
console.log(ContextMenuHandler.prototype.__proto__===EventTarget.prototype);//false,原型对象的原型默认指向一个object对象
console.log(typeof ContextMenuHandler.prototype.__proto__);//object