Zichen Ma
Zichen Ma

Reputation: 987

self create js library object is undefined

I am practicing to build a small js library like jQuery. When using a IIFE, the object: Todo, I created, is not defined. Code is sample, but really don't know what happened. Anyone can help me with this? Thank you so much!

HTML:

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="todo.js"></script>
</head>
<body>
<script type="text/javascript">
    Todo.print(); //Todo is not defined
</script>
</body>
</html>

js:

(function (window) {
    "use strict";
    function defineTodo () {
        var Todo = {};
        Todo.print = function () {
            console.log("To do");
        };
        return Todo;
    }

    if (typeof(defineTodo) === "undefined") {
            window.Todo = defineTodo();
    }
})(window);

Upvotes: 1

Views: 103

Answers (2)

Sagiv b.g
Sagiv b.g

Reputation: 31024

This line

if (typeof(defineTodo) === "undefined") {

Will always return false, hence you are not attaching Todo with defineTodo().
A better condition in my opinion could be:

 window.Todo = window.Todo || defineTodo();

See a running example:

(function(window) {
  "use strict";

  function defineTodo() {
    var Todo = {};
    Todo.print = function() {
      console.log("To do");
    };
    return Todo;
  }
  window.Todo = window.Todo || defineTodo();
})(window);

Todo.print(); //Todo is not defined

Upvotes: 1

JohanP
JohanP

Reputation: 5472

Your if is the problem. Change it to check if Todo is undefined and not the function i.e.

if (typeof(window.Todo) === "undefined")

Upvotes: 1

Related Questions