The new operator lets developers create an instance of a user-defined object type or of one of the built-in object types that has a constructor function. The new keyword does the following things:

  • Creates a blank, plain JavaScript object;
  • Links (sets the constructor of) this object to another object;
  • Passes the newly created object from Step 1 as the this context;
  • Returns this if the function doesn"t return its own object.
  • Syntax new constructor [([ arguments ])] Parameters constructor A class or function that specifies the type of the object instance. arguments A list of values that the constructor will be called with. Description

    Creating a user-defined object requires two steps:

  • Define the object type by writing a function.
  • Create an instance of the object with new .
  • To define an object type, create a function for the object type that specifies its name and properties. An object can have a property that is itself another object. See the examples below.

    When the code new Foo (...) is executed, the following things happen:

  • A new object is created, inheriting from Foo .prototype .
  • The constructor function Foo is called with the specified arguments, and with this bound to the newly created object. new Foo is equivalent to new Foo () , i.e. if no argument list is specified, Foo is called without arguments.
  • The object (not null, false, 3.1415 or other primitive types) returned by the constructor function becomes the result of the whole new expression. If the constructor function doesn"t explicitly return an object, the object created in step 1 is used instead. (Normally constructors don"t return a value, but they can choose to do so if they want to override the normal object creation process.)
  • You can always add a property to a previously defined object. For example, the statement car1.color = "black" adds a property color to car1 , and assigns it a value of " black ". However, this does not affect any other objects. To add the new property to all objects of the same type, you must add the property to the definition of the Car object type.

    You can add a shared property to a previously defined object type by using the Function.prototype property. This defines a property that is shared by all objects created with that function, rather than by just one instance of the object type. The following code adds a color property with value "original color" to all objects of type Car , and then overwrites that value with the string " black " only in the instance object car1 . For more information, see prototype .

    Function Car() {} car1 = new Car(); car2 = new Car(); console.log(car1.color); // undefined Car.prototype.color = "original color"; console.log(car1.color); // "original color" car1.color = "black"; console.log(car1.color); // "black" console.log(Object.getPrototypeOf(car1).color); // "original color" console.log(Object.getPrototypeOf(car2).color); // "original color" console.log(car1.color); // "black" console.log(car2.color); // "original color"

    If you didn"t write the new operator, the Constructor Function would be invoked like any Regular Function, without creating an Object. In this case, the value of this is also different.

    Examples Object type and object instance

    Suppose you want to create an object type for cars. You want this type of object to be called Car , and you want it to have properties for make, model, and year. To do this, you would write the following function:

    Function Car(make, model, year) { this.make = make; this.model = model; this.year = year; }

    Now you can create an object called myCar as follows:

    Var myCar = new Car("Eagle", "Talon TSi", 1993);

    This statement creates mycar and assigns it the specified values for its properties. Then the value of mycar.make is the string "Eagle", mycar.year is the integer 1993, and so on.

    You can create any number of car objects by calls to new . For example:

    Var kensCar = new Car("Nissan", "300ZX", 1992);

    Object property that is itself another object

    Suppose you define an object called Person as follows:

    Function Person(name, age, sex) { this.name = name; this.age = age; this.sex = sex; }

    And then instantiate two new Person objects as follows:

    Var rand = new Person("Rand McNally", 33, "M"); var ken = new Person("Ken Jones", 39, "M");

    Then you can rewrite the definition of Car to include an owner property that takes a Person object, as follows:

    Function Car(make, model, year, owner) { this.make = make; this.model = model; this.year = year; this.owner = owner; }

    To instantiate the new objects, you then use the following:

    Var car1 = new Car("Eagle", "Talon TSi", 1993, rand); var car2 = new Car("Nissan", "300ZX", 1992, ken);

    Instead of passing a literal string or integer value when creating the new objects, the above statements pass the objects rand and ken as the parameters for the owners. To find out the name of the owner of car2 , you can access the following property:

    Car2.owner.name

    Specifications Specification Status Comment
    ECMAScript Latest Draft (ECMA-262)
    Draft
    ECMAScript 2015 (6th Edition, ECMA-262)
    The definition of "The new Operator" in that specification.
    Standard
    ECMAScript 5.1 (ECMA-262)
    The definition of "The new Operator" in that specification.
    Standard
    ECMAScript 3rd Edition (ECMA-262)
    The definition of "The new Operator" in that specification.
    Standard
    ECMAScript 1st Edition (ECMA-262)
    The definition of "The new Operator" in that specification.
    Standard Initial definition. Implemented in JavaScript 1.0.
    Browser compatibility

    The compatibility table on this page is generated from structured data. If you"d like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

    Update compatibility data on GitHub

    Desktop Mobile Server Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js new
    Chrome Full support 1 Edge Full support 12 Firefox Full support 1 IE Full support 3 Opera Full support Yes Safari Full support Yes WebView Android Full support 1 Chrome Android Full support 18 Firefox Android Full support 4 Opera Android Full support Yes Safari iOS Full support Yes Samsung Internet Android Full support 1.0 nodejs Full support Yes

    Я не очень доволен JavaScript.

    • без заданных операций
    • наследование не так просто, как в Python
    • определения вложенных функций, обратные вызовы, трудно отлаживать

    Обязательные функции:

    • Открытый исходный код
    • должен работать в браузере без дополнительного плагина

    Alejandro

    Я сомневаюсь, что что-то еще существует, по крайней мере, с поддержкой JS. По сути, браузеры уже давно объявили JavaScript стандартом де-факто. Текущие браузеры не интерпретируют любой другой язык. Единственная «альтернатива», о которой я могу подумать, это VBScript, работающий под Internet Explorer, которого больше нигде нет.

    guettli

    @Alejandro AFAIK есть языки, которые "компилируются" в JS. Но я понятия не имею о состоянии дел.

    Ответы CAD97

    Единственный язык, который может переносить текущую цель JavaScript в браузерах, - это JavaScript. Убедитесь, что вы используете новейший стандарт ECMAScript (ES2016 / 2017) и используете переносчик, такой как BabelJS, для вывода JS в соответствии с более ранним стандартом, если это необходимо.

    Если этого вам недостаточно, другие языки могут компилироваться в JavaScript.

    Это январь 2017 года, и та магия WebAssembly, которую я предсказал, придет в себя. Вы по-прежнему не можете легко получить доступ к веб-API, но

    Mawg

    [Обновление до принятого ответа для будущих читателей]:

    Как и предсказывалось @ CAD97, WebAssembly теперь поддерживается во всех основных браузерах.

    Если вы хотите уменьшить количество JS, которое вы кодируете (вы не можете полностью исключить его), то Google для WebAssembly, если вы можете кодировать на C, C ++ или Rust.

    Вот очень простой пример из этого урока :

    Возьмите код C:

    #include #include #include #include int main(int argc, char ** argv) { printf("WebAssembly module loaded\n"); } int EMSCRIPTEN_KEEPALIVE roll_dice() { srand (time(NULL)); return rand() % 6 + 1; }

    скомпилируйте его в WebAssembly с помощью команды emcc dice-roll.c -s WASM=1 -O3 -o index.js

    и вызовите WebAssembly вашего кода C в вашем HTML:

    WebAssembly Example

    Пока еще рано для WebAssembly, но есть хорошие учебники вокруг. И, очевидно, мы скоро будем отлаживать этот C-код в браузере, так же как мы отлаживаем наш JS сегодня.

    Единственным недостатком является то, что можно обмениваться только числами, поэтому в настоящее время передача / возврат объектов и структур означает написание некоторого кода преобразования, но я уверен, что очень скоро появятся некоторые общие библиотечные функции для этого.

    CAD97

    Я фактически сделал минимальное количество WebAssembly с Rust. Это.... интересная экосистема прямо сейчас. Много растущих болей.

    Mawg

    Я ищу некоторые библиотеки, чтобы облегчить перевод сложных типов данных. На самом деле, я думаю, что я опубликую вопрос с таким вопросом позже сегодня.

    BrenBarn WebAssembly пытается заменить JavaScript?

    Нет! WebAssembly призван дополнять, а не заменять JavaScript. Хотя WebAssembly со временем позволит компилировать многие языки в Web, JavaScript имеет невероятный импульс и останется единственным привилегированным (как описано выше) динамическим языком Web. Кроме того, ожидается, что JavaScript и WebAssembly будут использоваться вместе в ряде конфигураций:

    • Целые, скомпилированные приложения C ++, использующие JavaScript для склеивания вещей.
    • HTML / CSS / JavaScript UI вокруг основного централизованного холста, контролируемого WebAssembly, что позволяет разработчикам использовать возможности веб-фреймворков для создания доступных, ощущений веб-нативного восприятия.
    • В основном приложение HTML / CSS / JavaScript с несколькими высокопроизводительными модулями WebAssembly (например, графики, симуляция, обработка изображений / звука / видео, визуализация, анимация, сжатие и т. Д., Примеры, которые мы уже видим в asm.js сегодня) позволяя разработчикам повторно использовать популярные библиотеки WebAssembly так же, как библиотеки JavaScript сегодня.
    • Когда WebAssembly получает возможность доступа к объектам, собираемым мусором 🦄 , эти объекты будут доступны для JavaScript, а не будут жить в собственном изолированном мире.
    Классы

    Class Point: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return "({x}, {y})".format(x=self.x, y=self.y)

    Class Point { constructor(x, y) { this.x = x; this.y = y; } toString() { return `(${this.x}, ${this.y})`; } }

    Подклассы

    Class ColorPoint(Point): def __init__(self, x, y, color): super().__init__(x, y) self.color = color def __str__(self): return "{super} in color {color}".format(super=super().__str__(), color=self.color)

    Class ColorPoint extends Point { constructor(x, y, color) { super(x, y); this.color = color; } toString() { return `${super.toString()} in ${this.color}`; } }

    Эти примеры касаются вашей болевой точки наследования. Современный JavaScript может выражать классы и наследование почти идентично Python.

    Для операций над множеством, см. Объект Set (совместимость). MDN предлагает базовые реализации операций над множествами :

    Set.prototype.isSuperset = function(subset) { for (var elem of subset) { if (!this.has(elem)) { return false; } } return true; } Set.prototype.union = function(setB) { var union = new Set(this); for (var elem of setB) { union.add(elem); } return union; } Set.prototype.intersection = function(setB) { var intersection = new Set(); for (var elem of setB) { if (this.has(elem)) { intersection.add(elem); } } return intersection; } Set.prototype.difference = function(setB) { var difference = new Set(this); for (var elem of setB) { difference.delete(elem); } return difference; }

    Или альтернативные неразрушающие реализации:

    Set.prototype.union = that => new Set([...this, ...that]) Set.prototype.intersection = that => new Set(this.values().filter(it => that.has(it))) Set.prototype.difference = that => new Set(this.values().filter(it => !that.has(it)))

    Вы не можете перегружать операторы, но это потому, что Object + Object уже четко определен (чтобы привести оба оператора к примитивному значению, а затем + этим значениям).

    Ваша последняя проблема - трудность отладки асинхронного кода JavaScript. К сожалению, большая часть этого заключается в том, что асинхронный код трудно отлаживать. Однако, если вы используете Promises и async / await , вы можете написать асинхронный код, точно так же, как PEP 492 Coroutines с async и await . Асинхронность просто трудно рассуждать в целом, и это не ошибка JavaScript здесь.

    Хитрость в том, чтобы использовать все тонкости современного ECMAScript, состоит в том, чтобы использовать Babel для преобразования ваших модных современных синтаксисов в совместимый с браузером JavaScript. Если вы хотите, чтобы язык работал на веб-сайте, обеспечивающем интерактивность веб-сайта, единственным вариантом является JavaScript, по крайней мере, до тех пор, пока WASM не достигнет того уровня, когда у него будет GC и взаимодействие объектов с JavaScript, что позволит использовать методы DOM в WASM.

    Скотт Стенсленд

    Чтобы решить проблему с вложенными определениями функций и их обратными вызовами, вы должны начать использовать понятие обещания javascript, что довольно приятно - это устраняет ад обратного вызова

    Javascript это практически вездесущий язык программирования. В некотором роде его можно сравнить с C на пике его популярности. На нем можно писать всё что угодно, начиная от красивых выпадающих менюшек, слайдеров на вашем сайте, заканчивая полноценнами приложениями для серверов, мобильных, для десктопа и даже для embedded систем типа arduino .

    Но у яваскрипта есть свои заковырки. Прототипная модель объектов, динамические типы, колбек-функции, всё это, можно сказать, на любителя. В результате начали появлятся альтернативные языки, предлагающие свои подходы к реализации тех или иных концептов. В этом посте перечислены самые популярные альтернативы теплому ванильному яваскрипту.


    Например, если вам хочется классического ООП, вместо прототипов, или вы хотите больше синтаксического сахара, посмотрите в сторону CoffeeScript . Если вам нужна строгая типизация вам могут понравиться Dart или TypeScript . К слову сказать, Dart работает нативно в Google Chrome и на некоторых тестах показывает 50% прирост производительности по сравнению с обычным javascript. Для любителей функциональго программирования подойдет ClojureScript или Roy . Вариантов масса, и вы не обязаны писать всё на чистом яваскрипте, даже если разрабатываете фронтенд под веб или работаете с node.js.

    4. ClojureScript ClojureScript - это расширение языка Clojure, с возможностью компиляции в Javascript. Напоминает Lisp.

    IcedCoffeeScript это надстройка над CoffeeScript, упрощающая контроль за асинхронными операциями. Вместо колбеков вводятся два новых оператора: await и defer.

    Ну и конечно, есть ещё один язык, самый главный в этой семье. Это, конечно же, сам Javascript. Как ни крути, а именно он будет выполнятся в браузере. Тем не менее, для использования в больших проектах стоить посмотреть в сторону Dart (поддерживаемый Google) или TypeScript (поддерживается Microsoft). CoffeeScript очень популярен в последнее время, а с помощью работать с ним стало ещё проще. Если вы устали от яваскрипта или хотите попробовать чего-то новенького, милости просим.

    PS. Обзор подготовлен с использованием каталога javascript-библиотек Jster.Net . Сейчас в нем уже 981 билиотека для фронтенд-разработки.

    Javascript это практически вездесущий язык программирования. В некотором роде его можно сравнить с C на пике его популярности. На нем можно писать всё что угодно, начиная от красивых выпадающих менюшек, слайдеров на вашем сайте, заканчивая полноценнами приложениями для серверов, мобильных, для десктопа и даже для embedded систем типа arduinio .

    Но у яваскрипта есть свои заковырки. Прототипная модель объектов, динамиеские типы, колбек-функции, всё это, можно сказать, на любителя. В результате начали появлятся альтернативные языки, предлагающие свои подходы к реализации тех или иных концептов. В этом посте перечислены самые популярные альтернативы теплому ванильному яваскрипту.

    Например, если вам хочется классического ООП, вместо прототипов, или вы хотите больше синтаксического сахара, посмотрите в сторону CoffeeScript . Если вам нужна строгая типизация вам могут понравиться Dart или TypeScript . К слову сказать, Dart работает нативно в Google Chrome и на некоторых тестах показывает 50% прирост производительности по сравнению с обычным javascript. Для любителей функциональго программирования подойдет ClojureScript или Roy . Вариантов масса, и вы не обязаны писать всё на чистом яваскрипте, даже если разрабатываете фронтенд под веб или работаете с node.js.

    1. CoffeeScript 2. Dart 3. TypeScript 4. ClojureScript

    ClojureScript - это расширение языка Clojure, с возможностью компиляции в Javascript. Напоминает Lisp.

    5. Opal 6. IcedCoffeeScript

    IcedCoffeeScript это надстройка над CoffeeScript, упрощающая контроль за асинхронными операциями. Вместо колбеков вводятся два новых оператора: await и defer.

    7. LiveScript 8. Kaffeine


    Расширяет синтакс яваскрипта, не изобретая ещё один язык программирования. Код на Kaffeine строка к строке соответствует скомпилированому яваскрипт коду. Данная фича должна существенно упростить отладку приложения.

    The problem with javascript is not the language itself - it"s a perfectly good prototyped and dynamic language. If you come from an OO background there"s a bit of a learning curve, but it"s not the language"s fault.

    Most people assume that Javascript is like Java because it has similar syntax and a similar name, but actually it"s a lot more like lisp. It"s actually pretty well suited to DOM manipulation.

    The real problem is that it"s compiled by the browser, and that means it works in a very different way depending on the client.

    Not only is the actual DOM different depending on the browser, but there"s a massive difference in performance and layout.

    Edit following clarification in question

    Suppose multiple interpreted languages were supported - you still have the same problems. The various browsers would still be buggy and have different DOMs.

    In addition you would have to have an interpreter built into the browser or somehow installed as a plug in (that you could check for before you served up the page) for each language. It took ages to get Javascript consistent.

    You can"t use compiled languages in the same way - then you"re introducing an executable that can"t easily be scrutinised for what it does. Lots of users would choose not to let it run.

    OK, so what about some sort of sandbox for the compiled code? Sounds like Java Applets to me. Or ActionScript in Flash. Or C# in Silverlight.

    What about some kind of IL standard? That has more potential. Develop in whatever language you want and then compile it to IL, which the browser then JITs.

    Except, Javascript is kind of already that IL - just look at GWT . It lets you write programs in Java, but distribute them as HTML and JS.

    Edit following further clarification in question

    Javascript isn"t, or rather wasn"t, the only language supported by browsers: back in the Internet Explorer dark ages you could choose between Javascript or VBScript to run in IE. Technically IE didn"t even run Javascript - it ran JScript (mainly to avoid having to pay Sun for the word java , Oracle still own the name Javascript ).

    The problem was that VBScript was proprietary to Microsoft, but also that it just wasn"t very good. While Javascript was adding functionality and getting top rate debugging tools in other browsers (like FireBug) VBScript remained IE-only and pretty much un-debuggable (dev tools in IE4/5/6 were none existent). Meanwhile VBScript also expanded to become a pretty powerful scripting tool in the OS, but none of those features were available in the browser (and when they were they became massive security holes).

    There are still some corporate internal applications out there that use VBScript (and some rely on those security holes), and they"re still running IE7 (they only stopped IE6 because MS finally killed it off).

    Getting Javascript to it"s current state has been a nightmare and has taken 20 years. It still doesn"t have consistent support, with language features (specified in 1999) still missing from some browsers and lots of shims being required.

    Adding an alternate language for interpreting in browsers faces two major problems:

      Getting all the browser vendors to implement the new language standard - something they still haven"t managed for Javascript in 20 years.

      A second language potentially dilutes the support you already have, allowing (for instance) IE to have second rate Javascript support but great VBScript (again). I really don"t want to be writing code in different languages for different browsers.

    It should be noted that Javascript isn"t "finished" - it"s still evolving to become better in new browsers. The latest version is years ahead of of the browsers" implementations and they"re working on the next one.


    Close