Javascript构造函数有什么意义?
Please provide your thoughts with respect to Javascript only! I am aware of classes and classical inheritance but not at a great detail.
请提供您对Javascript的想法!我知道类和经典继承但不是很详细。
As far as I know, constructors are used as prototypes for other objects. For example, I could create a car constructor and give it objects such as hondaCivic, toyotaCamry, etc. Are there any other important things I should know about constructors?
据我所知,构造函数被用作其他对象的原型。例如,我可以创建一个汽车构造函数并为其提供诸如hondaCivic,toyotaCamry等对象。我还应该了解有关构造函数的其他重要事项吗?
Furthermore,
- What is the purpose of a constructor, apart from what I have already stated?
- What are the benefits / disadvantages of a constructor?
除了我已经陈述的内容之外,构造函数的目的是什么?
构造函数的好处/缺点是什么?
3 个解决方案
#1
5
A constructor is just a normal function. There is nothing special about it inherently.
构造函数只是一个普通的函数。它本身并没有什么特别之处。
All functions have a property called prototype
.
所有函数都有一个名为prototype的属性。
If you write
如果你写
var myInstance = new MyFuction();
JavaScript does something special with your function when it executes it.
JavaScript在执行它时会对您的函数执行一些特殊操作。
It sets the value of this
inside the function body to be myInstance
. Additionally, it creates a reference to MyFunction.prototype
and stores it as an internal property of myInstance
.
它将函数体内的this值设置为myInstance。此外,它还创建了对MyFunction.prototype的引用,并将其存储为myInstance的内部属性。
When your code is executing, the rule that the interpreter follows is such that, if you try to access a property on myInstance
that it can't find, it will follow that reference to the function's prototype
and look there. This forms a chain, known as the prototype chain that leads all the way up to Object.prototype
.
当您的代码执行时,解释器遵循的规则是,如果您尝试访问myInstance上无法找到的属性,它将遵循对该函数原型的引用并查看。这形成了一个链,称为原型链,一直到Object.prototype。
Here's an example:
这是一个例子:
function Dog(name, breed) {
this.name = name;
this.breed = breed;
//if you don't specify a return value, `this` will be returned
}
Dog.prototype.speak = function() {
alert('Ruff, I\'m ' + this.name + ' the talking ' + this.breed);
}
var myDog = new Dog('buttercup', 'poodle');
myDog.speak();
更多相关文章
- 深入理解javascript函数进阶系列第二篇——函数柯里化
- 在Servlet和HTML页面之间处理函数调用和数据传输的最佳方法是什
- 使用HTML文件中的React调用.js文件中的Javascript函数
- 使用单个函数隐藏多个输入
- 如何从控制器内的javascript函数调用角范围函数
- JavaScript面向对象程序设计三——原型模式(上)
- 在传递给google.setOnLoadCallback()的函数中使用参数;
- 另一个iframe中的iframe的onload函数
- JavaScript 中的函数介绍