سؤال

I can't even find a hint of an answer to this question anywhere, so maybe I'm totally barking up the wrong tree...

I'm making a javascript namespace, inside of which I am putting a constructor function:

var SEP=SEP||{};

SEP.person=function(name)
{
    this.name=name
    this.sayName=sayName

    function sayName()
    {
        return this.name;
        $(document).ready
        (
            function()
            {
                $('body').css('background', 'red');
            }
        );
    }
}

Then I am calling the function from the HTML...

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>test</title>
<meta name="generator" content="BBEdit 10.5" />
</head>
<body>
<script src="libraries/jquery/javascript/jquery-1.11.0-min.js"></script>
<script src="libraries/sep/javascript/sep.js"></script>
<p>Hello</p>
<script>
    var bob=new SEP.person("bob");
    word=bob.sayName();
    document.write(word);
</script>
</body>
</html>

Question one is, why doesn't this work? Question two is how can I make it work? Question three is, if I want to make a more involved constructor, with JQuery peppered thoughout, do I need to do the document ready thing over and over, or is there a better way?

Many thanks in advance.

هل كانت مفيدة؟

المحلول

Actually your constructor is working fine. But you should not use document.write in your code. Instead you can append the value to a html tag, using either .append() .html() or .text() methods. Also there should be a small change in your sayName() method, Css should apply before return. Otherwise it will not hit on those lines of code.

var SEP = SEP || {};

SEP.person = function (name) {
    this.name = name
    this.sayName = sayName

    function sayName() {
        $('body').css('background', 'red');
        return this.name;
    }
}

var bob = new SEP.person("bob");
word = bob.sayName();
$("span").text(word);

Demo

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top