我发帖是因为对几个概念缺乏理解,也是为了检查我对此代码的描述是否准确。
首先,我创建了名为 contactForm 的父对象。我已将此对象设置为等于使用文字表示法的对象文字,即使用 { } 创建一个新对象并在括号内定义属性。
然后我有 init 方法。如果您熟悉面向对象编程,那么这将与您的构造函数方法相同。
现在下一部分是我感到困惑的地方。我正在使用 jQuery 创建一个新元素,即按钮标签。这个新创建的元素是名为 contactForm 的父对象内部的对象吗?
我的第二个问题是我是否传递了一个将文本设置为“联系我!”的参数到 contactForm 对象还是按钮元素/对象?
我的最后一个问题 - 传递给对象的参数是否也可以称为该对象的属性?
抱歉,如果我的术语描述不够充分或不够准确。任何简洁且解释清楚的答案将不胜感激。
var contactForm = {
init: function() {
$('<button></button>', {
text: 'Contact Me!'
})
.insertAfter('article:first');
}
};
最佳答案
First I have created parent object called contactForm. I've made this object equal to an object literal which uses literal notation that is, creating a new object with { } and defining properties within the brackets.
您有一个对象,在您的代码中由对象 literal 描述。 ,并将其分配给变量 contactForm
。不知道为什么你会称其为“父”。
Then I have the init method. If you’re familiar with object orientated programming that would be the same things as your constructor method.
你的对象有一个名为“init”的属性,它是一个函数 - 方便地称为“方法”。然而,JavaScript 中的构造函数的工作方式有点不同 - 每个函数在使用 new
operator 调用时都可以构造对象。 。当然,当声明单例实例(作为文字)时,通常会使用专用的初始化方法。
Now the next part is where is where I am confused. I am using jQuery to create a new element which are the button tags. Is this newly created element an object inside of the parent object called contactForm?
没有。您在 init
函数中所做的事情(首先)与 contactForm
对象无关。您正在调用jQuery
函数,它返回一个对象,您可以在该对象上调用 insertAfter
方法,并且由于您没有对该函数的结果执行任何操作,因此它会被垃圾收集。
My second question is am I passing a parameter that sets the text to 'Contact Me!' to the contactForm object or the button element/object?
您正在传递两个参数:一个字符串和一个对象。您的代码不知道 jQuery 函数如何处理这些参数。根据the documentation (对于代码,如果您真的想深入了解),这将创建一个 button
元素(包装在 jQuery 实例中)并调用它的 text
方法。
My final question - is it the case that the parameter passed to the object can also be called a property of that object?
没有。您将参数传递给函数。函数可能会将它们设置为返回对象的属性,但这取决于函数。无论如何,它们不被称为“函数对象的属性”。
关于javascript - jQuery 对象和参数 - 使用正确的术语/解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12638186/