我正在阅读有关 javascript 原型(prototype)的文章 http://phrogz.net/js/classes/OOPinJS.html我读到我们不能在 javascript 的对象构造函数中分配公共(public)方法?原型(prototype)方法与静态方法有何不同以及使用它们的优点是什么?
最佳答案
I read that we can not assign public methods inside a object constructor in javascript?
是的,文章提到了这一点:
function MyObj(name)
{
this.name = name;
}
MyObj.prototype.sayHello = function() {
alert('hello ' + this.name);
}
new MyObj('world').sayHello();
如您所见,公共(public)方法 sayHello()
是在原型(prototype)中声明的,这是在构造函数外部完成的。这就是 JavaScript 的工作原理。
How prototypal methods are different from static methods and what are the advantage of using them ?
原型(prototype)方法仅“附加”到对象。对于静态方法,您需要使用此构造:
var MyStaticThing = {
name: 'world',
sayHello: function() {
alert('hello ' + this.name);
}
}
MyStaticThing.sayHello();
关于javascript - 我们可以在对象构造函数中分配一个公共(public)方法吗? (javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14929314/