为什么我们不能通过 obj.prototype.function() 访问函数,为什么原型函数不能访问 'this'?
Why can't we access function via obj.prototype.function(), why prototype function can't access 'this'?
3 个不同的调用有何不同?
let Person=function(name){
this.name=name;
};
Person.prototype.func=function(){
console.log('Hey I am '+this.name);
};
let jay=new Person("jay");
jay.func(); /*This Works*/
jay.__proto__.func(); /*This doesn't have access to this.name? why?*/
jay.prototype.func(); /*This gives error, Why?*/
当你这样做时
jay.__proto__.func();
您调用 func
函数时调用上下文是最后一个点之前的所有内容:也就是说,this
为 jay.__proto__
,这与Person.prototype
:
let Person=function(name){
this.name=name;
};
Person.prototype.func=function(){
console.log(this === Person.prototype);
console.log(this === jay.__proto__);
};
let jay=new Person("jay");
jay.__proto__.func();
name
属性 在 jay
实例本身上。它不在原型上,因此当 this
是原型时在方法内部引用 this.name
不会显示实例的 name
属性。
如果您改用 .call
,您也可以使用正确的 this
进行调用:jay.__proto__.func.call(jay);
,这将调用 this
设置为jay
不是 jay.__proto__
。
jay.prototype.func();
/This gives error, Why?/
.prototype
属性有点乱。它通常只有在它是 函数 的 属性 时才有意义,在这种情况下,从该函数创建的实例具有 内部原型 该原型对象的(或 __proto__
)。
在正常实例和几乎所有其他地方,.prototype
属性 并不意味着任何特殊的东西,可能不会存在。所以在 jay.prototype
.
没有任何东西存在
3 个不同的调用有何不同?
let Person=function(name){
this.name=name;
};
Person.prototype.func=function(){
console.log('Hey I am '+this.name);
};
let jay=new Person("jay");
jay.func(); /*This Works*/
jay.__proto__.func(); /*This doesn't have access to this.name? why?*/
jay.prototype.func(); /*This gives error, Why?*/
当你这样做时
jay.__proto__.func();
您调用 func
函数时调用上下文是最后一个点之前的所有内容:也就是说,this
为 jay.__proto__
,这与Person.prototype
:
let Person=function(name){
this.name=name;
};
Person.prototype.func=function(){
console.log(this === Person.prototype);
console.log(this === jay.__proto__);
};
let jay=new Person("jay");
jay.__proto__.func();
name
属性 在 jay
实例本身上。它不在原型上,因此当 this
是原型时在方法内部引用 this.name
不会显示实例的 name
属性。
如果您改用 .call
,您也可以使用正确的 this
进行调用:jay.__proto__.func.call(jay);
,这将调用 this
设置为jay
不是 jay.__proto__
。
jay.prototype.func();
/This gives error, Why?/
.prototype
属性有点乱。它通常只有在它是 函数 的 属性 时才有意义,在这种情况下,从该函数创建的实例具有 内部原型 该原型对象的(或 __proto__
)。
在正常实例和几乎所有其他地方,.prototype
属性 并不意味着任何特殊的东西,可能不会存在。所以在 jay.prototype
.