【发布时间】:2017-01-04 08:38:33
【问题描述】:
所以,使用 Code Academy 时,我在 Javascript 教程的对象部分,我很难将我的大脑包裹在函数和对象上。我想要一些帮助并用下面的部分代码进行解释。我已经评论了每一行我需要帮助的地方。提前非常感谢。
// Obviously declaring the Rabbit function with adjective to be called
function Rabbit(adjective) {
// I don't understand this line, or the context of why this is being used.
this.adjective = adjective;
// Why declare another function here? Is a function within a function
// considered a Method or is that only Function within an Object?
this.describeMyself = function() {
// I get this part but why does it need a function to do this?
console.log("I am a " + this.adjective + " rabbit");
};
}
// I don't get this either, Isn't this declaring a new object? How can
// that be when you only have a Function named Rabbit?
var rabbit1 = new Rabbit("fluffy");
var rabbit2 = new Rabbit("happy");
var rabbit3 = new Rabbit("sleepy");
// How could this work if describeMyself is in the Rabbit function and
// has nothing to do with rabit1?
console.log(rabbit1.describeMyself);
console.log(rabbit2.describeMyself);
console.log(rabbit3.describeMyself);
希望不要太令人困惑,但如果你们中的任何一位更有经验的 Javascript 人员可以解释我在 cmets 中谈到的所有内容,我将不胜感激。谢谢
【问题讨论】:
-
编程语言中的“方法”通常是作为对象的属性或子对象附加的函数(但定义 JavaScript 的 EMCAScript 规范从不使用“方法”一词来描述语言的任何特性; 这只是一个笼统的词)。对于其余部分,这通常由JavaScript: How does 'new' work internally 回答,尽管那里的答案可能已经假设您对语言有很强的掌握。简短的回答是
new使用新创建的this对象调用函数。 -
请注意,您的课程所教授的技术仍然有效,但最新版本的 Javascript 通常为considered superseded。但是,如果您有任何现代 OOP 语言(C++、Ruby、Java)的经验,应该很容易找到与它们的类、方法等概念的相似之处。但请注意,底层机制(原型委托)有很大不同.
-
纠正我之前的评论:规范实际上确实将“方法”明确定义为“作为属性值的函数”。 (我误以为它没有为该类函数提供这样的定义。)
标签: javascript function object javascript-objects