Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在javascript类中使用此选项_Javascript_Class_This - Fatal编程技术网

在javascript类中使用此选项

在javascript类中使用此选项,javascript,class,this,Javascript,Class,This,我是javascript的高手 我想知道为什么在javascript中定义属性和函数时必须使用这个。比如说 function Apple (type) { this.type = type; this.color = "red"; this.getInfo = function() { return this.color + ' ' + this.type + ' apple'; }; } var apple = new Apple('ma

我是javascript的高手

我想知道为什么在javascript中定义属性和函数时必须使用这个。比如说

   function Apple (type) {
    this.type = type;
    this.color = "red";
    this.getInfo = function() {
        return this.color + ' ' + this.type + ' apple';
    };
}

var apple = new Apple('macintosh');
apple.color = "reddish";
alert(apple.getInfo());
我知道这是指调用类的对象。我们在C++中使用了这个 JAVA我们定义了一个类似这样的类

class apple {
        char type ;
        char color ;
        returntype getInfo (){
          this.color = 'red';
           this.type = 'something'

    }
我认为在javascript中声明属性时使用它也很奇怪。
这背后有什么原因吗?

JavaScript中没有类。一切都是对象。因此,您需要操纵对象

使用
new
调用函数时:
将引用您可以编辑的新创建的对象

如果调用函数时不使用
new
,则在示例中,
实际上是
窗口(浏览器)或
全局
(服务器端)

要向对象添加新字段,通常需要执行以下操作:
object.newfield=somevalue
,但此处
object
存储在变量
this

过程类似于:

新函数
->
创建新对象
->
将其作为“this”传递给函数
->
函数工作
->
返回更新的“this”


函数工作
部分是函数代码实际执行的地方。

这是一个奇怪的JavaScript东西,所有东西都是对象。JavaScript中的“类”实际上只是一个对象的构造函数。若不使用this(仅Apple()或MyClass())调用它,则变量只是局部变量。当您开始添加OOP时,您会得到一个场景,在这个场景中,您需要能够区分对象属性和构造函数(或方法)的局部变量。因此,
this
关键字用于指向当前对象的引用(因此您访问的是对象的属性,而不是函数当前范围的属性)


或者。。因为有人这么说,我们这些程序员不得不接受它;)

它被建模为具有与Java相似的语法。问问设计师,这和Java是一样的,只是在Java中使用
this
是可选的,而且JavaScript没有明确的与定义分开的“构造函数”。你真正的问题是什么?如果你觉得这很奇怪,那么最好不要读关于原型的书。