gpt4 book ai didi

javascript 原型(prototype)链对此的困惑

转载 作者:行者123 更新时间:2023-12-03 03:42:52 26 4
gpt4 key购买 nike

查看下面的教程代码

Animal = function(name) {this.name = name}
Animal.prototype.eats = function(){
return this.name + ' is eating'
}

Chordate = function(name){Animal.call(this,name)}

我理解call是如何工作的(基本上,在这种情况下,这变成了this)...但我的问题是,如何使用它?很抱歉,我了解原型(prototype)是如何工作的。但实际上,一旦你按照上面的方式设置了 Chordate,我就不明白了。如何使用它?这有什么用?或者您现在打算如何指定 this?有人可以举例说明吗?

最佳答案

创建指向 Animal 原型(prototype)方法的链接:

Chordate.prototype = Object.create(Animal.prototype)

然后新建它:

var c = new Chordate('my name');

c.eats();

Animal.call(this,name) 行就像调用基本构造函数一样。它执行 Animal 构造函数并传入 name,但使用正确的 this 上下文:

Animal = function(name) {
// "this" will be your Chordate instance
this.name = name
}

关于javascript 原型(prototype)链对此的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45535787/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com