Is not a function javascript как исправить

It looks like "$smth is not a function" is a very common problem with JavaScript, yet after looking through quite a few threads I still cannot understand what is causing it in my case. I have a cu...

It looks like «$smth is not a function» is a very common problem with JavaScript, yet after looking through quite a few threads I still cannot understand what is causing it in my case.

I have a custom object, defined as:

function Scorm_API_12() {
var Initialized = false;

function LMSInitialize(param) {
    errorCode = "0";
    if (param == "") {
        if (!Initialized) {
            Initialized = true;
            errorCode = "0";
            return "true";
        } else {
            errorCode = "101";
        }
    } else {
        errorCode = "201";
    }
    return "false";
}

// some more functions, omitted.
}

var API = new Scorm_API_12();

Then in a different script I am trying to use this API in the following way:

var API = null;

function ScormProcessInitialize(){
    var result;

    API = getAPI();

    if (API == null){
        alert("ERROR - Could not establish a connection with the API.");
        return;
    }

    // and here the dreaded error pops up
    result = API.LMSInitialize("");

    // more code, omitted
    initialized = true;
}

The getAPI() stuff, looks like this:

var findAPITries = 0;

function findAPI(win)
{
   // Check to see if the window (win) contains the API
   // if the window (win) does not contain the API and
   // the window (win) has a parent window and the parent window
   // is not the same as the window (win)
   while ( (win.API == null) &&
           (win.parent != null) &&
           (win.parent != win) )
   {
      // increment the number of findAPITries
      findAPITries++;

      // Note: 7 is an arbitrary number, but should be more than sufficient
      if (findAPITries > 7)
      {
         alert("Error finding API -- too deeply nested.");
         return null;
      }

      // set the variable that represents the window being
      // being searched to be the parent of the current window
      // then search for the API again
      win = win.parent;
   }
   return win.API;
}

function getAPI()
{
   // start by looking for the API in the current window
   var theAPI = findAPI(window);

   // if the API is null (could not be found in the current window)
   // and the current window has an opener window
   if ( (theAPI == null) &&
        (window.opener != null) &&
        (typeof(window.opener) != "undefined") )
   {
      // try to find the API in the current window�s opener
      theAPI = findAPI(window.opener);
   }
   // if the API has not been found
   if (theAPI == null)
   {
      // Alert the user that the API Adapter could not be found
      alert("Unable to find an API adapter");
   }
   return theAPI;
}

Now, the API is probably found, because I do not get the «Unable to find…» message, the code proceeds to try to initialize it. But firebug tells me API.LMSInitialize is not a function, and if I try to debug it with alert(Object.getOwnPropertyNames(API));, it gives me a blank alert.

What am I missing?

The Javascript error TypeError: "x" is not a function occurs when there is an attempt to call a function on a value or object, which is not actually a function.

Error message:

TypeError: "x" is not a function

Error Type:

TypeError

What Causes TypeError: «x» is not a function

A TypeError: "x" is not a function in Javascript generally occurs in one of the following scenarios:

  • A typographical error in a function call.
  • Missing script library.
  • When a function is called on a property that is not actually a function.
  • A TypeError: "x" is not a function occurs when a function is called on an object that does not contain the called function.
  • When calling a built-in function that expects a callback function argument, which does not exist.
  • When the called function is within a scope that is not accessible

TypeError: «x» is not a function Examples

1. Typo

A typical scenario for the TypeError: "x" is not a function to occur is when there is a typo in the called function name:

var elem = document.getElementByID('ID');

Running the above code leads to the following Javascript error:

TypeError: document.getElementByID is not a function

The correct function name is getElementById():

var elem = document.getElementById('ID');

2. Object Does Not Contain Function

Another common cause for the TypeError: "x" is not a function is when a function is called an object that does not actually contain the function:

var foo = {
   bar: function() {
      console.log("bar called");
   }
};
foo.baz();

In the above example, the foo object contains a function bar(). However, the above code attempts to call the function baz(), which foo does not contain. Running the above code leads to the following Uncaught TypeError: "x" is not a function:

Uncaught TypeError: foo.baz is not a function

If the Javascript code is modified to call the correct function bar():

var foo = {
   bar: function() {
      console.log("bar called");
   }
};    
foo.bar();

The correct output is produced:

bar called

How to Fix Javascript TypeError: «x» is not a function

The TypeError: "x" is not a function can be fixed using the following suggestions:

  • Paying attention to detail in code and minimizing typos.
  • Importing the correct and relevant script libraries used in code.
  • Making sure the called property of an object is actually a function.
  • Making sure objects contain the called function to avoid TypeError: "x" is not a function.
  • Making sure functions passed in as callbacks do exist.
  • Making sure called functions are within the correct and accessible scope.

Track, Analyze and Manage Errors With Rollbar

Rollbar in action

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Javascript errors easier than ever. Sign Up Today!

TypeError:»x» не является функцией

Исключение JavaScript «не является функцией» возникает,когда была попытка вызвать значение из функции,но на самом деле значение не является функцией.

Message

TypeError: "x" is not a function. (V8-based & Firefox & Safari)

Error type

Что пошло не так?

Она пыталась вызвать значение из функции,но на самом деле значение не является функцией.Какой-то код ожидает,что вы предоставите функцию,но этого не произошло.

Может, в названии функции опечатка? Может быть, объект, для которого вы вызываете метод, не имеет этой функции? Например, у Objects JavaScript нет функции map , но у объекта Array JavaScript есть.

Существует множество встроенных функций,нуждающихся в функции (обратного вызова).Чтобы эти методы работали должным образом,вам необходимо предоставить функцию:

  • При работе с объектами Array или TypedArray :
    • Array.prototype.every(), Array.prototype.some(), Array.prototype.forEach(), Array.prototype.map(), Array.prototype.filter(), Array.prototype.reduce(), Array.prototype.reduceRight(), Array.prototype.find()
  • При работе с объектами Map и Set :
    • Map.prototype.forEach() и Set.prototype.forEach()

Examples

Ошибка в названии функции

В этом случае,что случается слишком часто,в названии метода присутствует опечатка:

const x = document.getElementByID('foo');

Правильное имя функции — getElementById :

const x = document.getElementById('foo');

Функция вызвана не на том объекте

Для определенных методов вы должны предоставить функцию (обратного вызова), и она будет работать только с определенными объектами. В этом примере используется Array.prototype.map() , который работает только с объектами Array .

const obj = { a: 13, b: 37, c: 42 };

obj.map(function (num) {
  return num * 2;
});


Вместо этого используйте массив:

const numbers = [1, 4, 9];

numbers.map(function (num) {
  return num * 2;
});


Функция разделяет имя с ранее существовавшей собственностью

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

function Dog() {
  this.age = 11;
  this.color = "black";
  this.name = "Ralph";
  return this;
}

Dog.prototype.name = function (name) {
  this.name = name;
  return this;
}

const myNewDog = new Dog();
myNewDog.name("Cassidy"); 

Вместо этого используйте другое имя свойства:

function Dog() {
  this.age = 11;
  this.color = "black";
  this.dogName = "Ralph"; 
  return this;
}

Dog.prototype.name = function (name) {
  this.dogName = name;
  return this;
}

const myNewDog = new Dog();
myNewDog.name("Cassidy"); 

Использование скобок для умножения

В математике 2 × (3+5)можно записать как 2*(3+5)или просто 2(3+5).

Использование последнего приведет к ошибке:

const sixteen = 2(3 + 5);
console.log(`2 x (3 + 5) is ${sixteen}`);

Вы можете исправить код, добавив оператор * :

const sixteen = 2 * (3 + 5);
console.log(`2 x (3 + 5) is ${sixteen}`);

Правильно импортируйте экспортированный модуль

Убедитесь,что вы правильно импортируете модуль.

Пример библиотеки помощников ( helpers.js )

const helpers = function () { };

helpers.groupBy = function (objectArray, property) {
  return objectArray.reduce((acc, obj) => {
    const key = obj[property];
    acc[key] ??= [];
    acc[key].push(obj);
    return acc;
  }, {});
}

export default helpers;

Правильное использование импорта ( App.js ):

import helpers from './helpers';

See also

  • Functions


JavaScript

  • RangeError:аргумент не является корректной кодовой точкой

    Исключение JavaScript «Недопустимая кодовая точка» возникает, когда значения NaN, отрицательные целые числа (-1), нецелые числа (5.4) или больше 0x10FFFF (1114111)

  • TypeError: «x» не является конструктором

    Исключение JavaScript «не является конструктором» возникает, когда была попытка использовать объектную переменную, но была попытка использовать объект или переменную

  • ReferenceError: «x» не определен

    Исключение JavaScript «переменная не определена» возникает, когда где-то есть несуществующая ссылка.

  • RangeError:точность вне досягаемости

    Исключение JavaScript «точность вне допустимого диапазона» возникает, когда число, выходящее за пределы 0 и 20 (или 21), было передано в toFixed toPrecision.

TypeError: «x» is not a function

The JavaScript exception «is not a function» occurs when there was an attempt to call a value from a function, but the value is not actually a function.

Message

TypeError: Object doesn't support property or method {x} (Edge)
TypeError: "x" is not a function

Error type

TypeError

What went wrong?

It attempted to call a value from a function, but the value is not actually a function. Some code expects you to provide a function, but that didn’t happen.

Maybe there is a typo in the function name? Maybe the object you are calling the method on does not have this function? For example, JavaScript Objects have no map function, but the JavaScript Array object does.

There are many built-in functions in need of a (callback) function. You will have to provide a function in order to have these methods working properly:

  • When working with Array or TypedArray objects:
    • Array.prototype.every(), Array.prototype.some(), Array.prototype.forEach(), Array.prototype.map(), Array.prototype.filter(), Array.prototype.reduce(), Array.prototype.reduceRight(), Array.prototype.find()
  • When working with Map and Set objects:
    • Map.prototype.forEach() and Set.prototype.forEach()

Examples

A typo in the function name

In this case, which happens way too often, there is a typo in the method name:

let x = document.getElementByID('foo');

The correct function name is getElementById:

let x = document.getElementById('foo');

Function called on the wrong object

For certain methods, you have to provide a (callback) function and it will work on specific objects only. In this example, Array.prototype.map() is used, which will work with Array objects only.

let obj = {a: 13, b: 37, c: 42};

obj.map(function(num) {
  return num * 2;
});


Use an array instead:

let numbers = [1, 4, 9];

numbers.map(function(num) {
  return num * 2;
});


Function shares a name with a pre-existing property

Sometimes when making a class, you may have a property and a function with the same name. Upon calling the function, the compiler thinks that the function ceases to exist.

var Dog = function () {
 this.age = 11;
 this.color = "black";
 this.name = "Ralph";
 return this;
}

Dog.prototype.name = function(name) {
 this.name = name;
 return this;
}

var myNewDog = new Dog();
myNewDog.name("Cassidy"); 

Use a different property name instead:

var Dog = function () {
 this.age = 11;
 this.color = "black";
 this.dogName = "Ralph"; 
 return this;
}

Dog.prototype.name = function(name) {
 this.dogName = name;
 return this;
}

var myNewDog = new Dog();
myNewDog.name("Cassidy"); 

Using brackets for multiplication

In math, you can write 2 × (3 + 5) as 2*(3 + 5) or just 2(3 + 5).

Using the latter will throw an error:

const sixteen = 2(3 + 5);
alert('2 x (3 + 5) is ' + String(sixteen));

You can correct the code by adding a * operator:

const sixteen = 2 * (3 + 5);
alert('2 x (3 + 5) is ' + String(sixteen));

Import the exported module correctly

Ensure you are importing the module correctly.

An example helpers library (helpers.js)

let helpers = function () { };

helpers.groupBy = function (objectArray, property) {
  return objectArray.reduce(function (acc, obj) {
    var key = obj[property];
    if (!acc[key]) {
      acc[key] = [];
    }
    acc[key].push(obj);
    return acc;
  },
{});
}

export default helpers;

The correct import usage (App.js):

import helpers from './helpers'

See also

  • Functions

Понравилась статья? Поделить с друзьями:
  • Is mf02 5 ошибка gta v
  • Is forbidden error looking up service account
  • Is fc05 fortnite ошибка установки
  • Is either not designed to run on windows or it contains an error
  • Is done dll ошибка как исправить при установке код ошибки 12