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' }
- 为什么函数sayName不在对象的实例中
- 为什么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
关键字的对象实例
- 创建一个新的空项目
- 空对象的原型链接与
Test
链接 - CCD_ 5的值绑定到CCD_
- 它执行构造函数,每当提到这一点时都使用新创建的对象
- 返回新创建的对象
- 如果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
函数。
最后,我真的建议你学习new
、Object.create
&prototype degation
。尽管class
关键字目前存在于javascript中,但它只是围绕new
关键字如何工作的语法糖,与class
在object oriented languages
(如java
(中如何工作的实现不同。IMO,我建议你更多地了解new , Object.create
,因为它们在现代代码中也非常常用:(
这篇文章值得注意