【发布时间】:2018-01-21 19:27:13
【问题描述】:
我在看tutorial about functions。还有一个例子
function Car(){
this.running = false
}
Car.prototype.start = function(){
this.running = true
}
Car.prototype.stop = function(){
this.running = false
}
var c = new Car()
c.running // false
c.start // true
c.running // true
但是还有另一种方法可以做同样的事情
function Car(){
this.running = false;
this.start = function(){
this.running = true
}
this.stop = function(){
this.running = false
}
}
var c = new Car()
c.running // false
c.start // true
c.running // true
问题:
- 与方法相比,使用原型的优缺点是什么?
- 我们应该在什么时候避免/使用原型?
- 我们什么时候应该避免/使用方法?
【问题讨论】:
-
我认为你的术语有点不对劲。方法是作为函数的对象属性 - 无论此属性是对象自己的属性还是对象原型的属性。
标签: javascript methods prototype