[英]Understanding function definitions inside object with different syntaxes in Javascript
[英]JavaScript OOP: Object instantiation and adding properties using different syntaxes
我正在尝试更深入地研究JavaScript OOP实践。 总的来说,我有这个想法,但是仍然存在一些问题,特别是关于对象实例化和方法添加的问题。
在创建构造函数时,我过去曾使用过这两个版本:
function MyConstructor(someArg) {
this.arg = someArg;
}
var MyConstructor = function(someArg) {
this.arg = someArg;
}
两者可以用相同的方式初始化,但是它们是否相同? 我问是因为在其中一个中,对象的名称是函数的名称,在另一个中,实际的对象是在匿名函数中创建的。
在向对象添加方法时,我遇到了几种变化,这确实使我感到困惑,因为我真的不知道它是不同的语法还是它们的工作方式不同。
这向MyConstructor
的原型添加了一个功能,这意味着所有实例都可以访问它,并且扩展MyConstructor
对象也因为它在原型链中而已。
MyConstructor.prototype.showArg = function() {
console.log(this.arg);
}
有时我也看到这样的事情:
MyConstructor.prototype = {
showArgument:function() {
console.log(this.arg);
},
};
这与第一个示例( MyConstructor.prototype.showArg = function()…
)相同吗?
然后,我还遇到了这样的语法,它对我不起作用–是因为showArg
仅添加到一个特定实例,而不添加到原型?
MyConstructor.showArg = function() {
console.log(this.arg);
}
另外,似乎也有一种jQuery的方式来做到这一点:
$.extend(MyConstructor.prototype, {
showArgument:function() {
console.log(this.arg);
},
});
这可能与前两个示例相同,因为它向原型添加了属性,对吗?
MyConstructor.prototype引用该对象。 当您分配它像
MyConstructor.prototype = {
showArgument:function() {
console.log(this.arg);
},
};
它实际上是使用showArgument作为一个属性创建一个新对象。 通过原型继承的所有其他默认属性都将丢失。 但是当你这样做
MyConstructor.prototype.showArg = function() {
console.log(this.arg);
}
这扩展了现有对象,使其具有附加属性showArg,其他属性保持不变。
jQuery的extend()API提供了一种扩展对象并为其添加属性的方法。 它更像是一种JQuery的处理方式。
原型示例绝对不是一回事。 在第二个示例中,您将除去 showArgument
函数之外的所有内容从原型中完全删除 。
仅集showArg
MyConstructor.prototype.showArg = function() {
console.log(this.arg);
}
将原型设置为仅 showArgument
MyConstructor.prototype = {
showArgument:function() {
console.log(this.arg);
},
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.