Javascript的新运算符除了使生活变得困难之外,还能做什么吗? [英] Does Javascript's new operator do anything but make life difficult?

查看:24
本文介绍了Javascript的新运算符除了使生活变得困难之外,还能做什么吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自传统的Web开发人员背景,在任何情况下我都不能声称自己真正了解Javascript,但是我正在尝试.

I come from the traditional web developer background where I can by no means claim to really know anything about Javascript, however I am trying.

我目前将其描述为对JQuery的新手理解,对闭包的稍微更好的理解,并且我已经通读了,觉得我对Douglas Crockford的"Javascript:The Good Parts"相当清楚.

I currently have what I would describe as a fairly novice understanding of JQuery, a slightly better understanding of closures, and I've read through, and feel like I am fairly clear on Douglas Crockford's "Javascript: The Good Parts".

我最近一直在建立一些JavaScript密集型页面,实际上我对结果非常满意.值得注意的一件事是,我几乎没有全局函数就完成了整个操作,甚至一次都没有使用过新的运算符.

I've been building up some fairly javascript intensive pages lately and I'm actually pretty satisfied with the results. One thing that stands to notice is that I managed to do the whole thing with almost no global functions and without using the new operator even once.

事实上,根据我对上述书籍的阅读,操作员没有做任何您不能做的更简单的方法,并迫使您破解"this"变量.

As a matter of fact, from my reading of the above-mentioned book, the operator does nothing that you could not do another simpler way and forces you to hack the 'this' variable.

那么我有什么想念的吗?新操作符实际上是为了达到目的还是使OO程序员对本质上是功能语言的内容感到满意的技巧?我最好完全从我的JS词汇表中删除它吗?

So is there something I'm missing? Does the new operator actually serve a purpose or is it just a trick to make OO programmers comfortable in what is at heart a functional language? Would I be better off striking it entirely from my JS vocabulary?

推荐答案

首先,对阅读Javascript:好的部分的赞誉,是一本关于语言的好书.

First of all, kudos on reading Javascript: The Good Parts it's a great book on the language.

要回答您的问题,如果要使用原型继承,则需要 new 运算符.没有其他方法可以使对象与另一个对象继承".话虽如此,您可以将属性从一个对象复制到另一个对象,这在某些情况下将不需要操作员.

To answer your question, the new operator is required if you want to make use of prototypal inheritance. There is no other way to have an object "inherit" from another. That being said, you can copy properties from one object to another that would remove the need for the operator in some cases.

例如,经典方法将使用以下内容:

For example, a classical approach would use the following:

function MyClass() {};
MyClass.prototype.sayHello = function() {
   alert('hello');
};


var o = new MyClass();
o.sayHello();

您可以实现以下相对相同的目的:

You can achieve relatively the same thing as follows:

function MyClass() {
   return { 
      sayHello: function() {
         alert('hello');
      }
   };
}

var o = MyClass();
o.sayHello();

这篇关于Javascript的新运算符除了使生活变得困难之外,还能做什么吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆