我是JavaScript的初学者,我发现一个非常令人困惑的概念.请考虑以下代码:
var person = {
firstName :"Penelope",
lastName :"Barrymore",
// Since the "this" keyword is used inside the showFullName method below, and the showFullName method is defined on the person object,?
// "this" will have the value of the person object because the person object will invoke showFullName ()?
showFullName:function () {
console.log (this.firstName + " " + this.lastName);
}
?
}
?
person.showFullName (); // Penelope Barrymore
Run Code Online (Sandbox Code Playgroud)
人是一个阶级或功能还是只是一个变量?
如果假设那个人是一个类,那么代码person.showFullName ();是调用它的正确方法,因为在C#或我们编写的任何其他语言中
person perObj = new person();
perObj.showFullName();
Run Code Online (Sandbox Code Playgroud)
?
在我的一个问题中,我得到以下代码作为答案之一.我对语言的理解现在变得更好了,只有一个小问题.
var person = function() {
this.firstName = "";
this.lastName = "";
}
person.prototype.showFullName = function () {
console.log(this.firstName + " " + this.lastName);
}
var perObj = new person();
perObj.firstName = "Penelope";
perObj.lastName = "Barrymore";
perObj.showFullName();
Run Code Online (Sandbox Code Playgroud)
考虑到对象,
var person = function() {
this.firstName = "";
this.lastName = "";
}
Run Code Online (Sandbox Code Playgroud)
当我用这个对象来称呼时,
var perObj = new person();
Run Code Online (Sandbox Code Playgroud)
这类似于构造函数的东西吗?
一刻代码
var perObj = new person();
Run Code Online (Sandbox Code Playgroud)
被调用会自动执行以下两行吗?
this.firstName = "";
this.lastName = "";
Run Code Online (Sandbox Code Playgroud)
而且在我正在研究的一个博客中,如果文件名是Samplescript.js,如果函数是使用相同的名称编写的var Samplescript=function(){},那么这个函数会被视为构造函数吗?请澄清一下这个.
尽管理论上事情很清楚,但实际上我并没有得到任何关于构造函数的令人满意的答案,在这个例子中,它的编写方式有很多清晰的理解.
考虑以下代码:
function Foo() {
return "something";
}
var foo = new Foo();
Run Code Online (Sandbox Code Playgroud)
根据 JavaScript 专家的说法,他们说从构造函数返回“nothing”或“this”。这是什么原因?
我知道当使用“new”时,“this”将被设置为构造函数的原型对象,但无法单独理解这一点。