为原型分配方法不起作用


function Test(){
this.name = "Hello World";
function sayName(){
return this.name;
}
}
Test.prototype.callName = function(){
return `Hello my name is, ${this.name}`;
}
const me = new Test();
me.callName();
console.log(me);

输出

Test { name: 'Hello World' }
  1. 为什么函数sayName不在对象的实例中
  2. 为什么me.callName((函数调用不起作用

为什么函数sayName不在对象的实例中。

因为您没有分配它。

this.sayName = sayName;

为什么me.callName((函数调用不能正常工作

IDK它适用于我

function Test(){
this.name = "Hello World";
this.sayName = function sayName(){
return this.name;
}
}
Test.prototype.callName = function(){
return `Hello my name is, ${this.name}`;
}
const me = new Test();
console.log(me.sayName());
console.log(me.callName());

这是因为您正在使用new关键字对Test()进行投影。当您创建使用new关键字的对象实例

  1. 创建一个新的空项目
  2. 空对象的原型链接与Test链接
  3. CCD_ 5的值绑定到CCD_
  4. 它执行构造函数,每当提到这一点时都使用新创建的对象
  5. 返回新创建的对象
  6. 如果CCD_ 7具有返回值,则返回该值

因此,在这个过程中,您实际上将this的值永久绑定到Test,因此this.name可以变成Test.name

如果只调用me = Test而不调用new,则不会发生this绑定。在这种情况下,this实际上指的是全局范围。

如果您已经编写了this.sayName = function sayName(){...},则可以访问sayName

me.callName通过行为委派工作。这是js的一个特性,如果没有在有问题的对象上定义行为,则可以指示要将行为委托给的对象。Test.callName不存在,因此它遍历原型链接,并在所使用的prototype对象中找到一个callName函数。

最后,我真的建议你学习newObject.create&prototype degation。尽管class关键字目前存在于javascript中,但它只是围绕new关键字如何工作的语法糖,与classobject oriented languages(如java(中如何工作的实现不同。IMO,我建议你更多地了解new , Object.create,因为它们在现代代码中也非常常用:(

这篇文章值得注意

最新更新