问题
Excuse my terminology if it's off. I don't understand the difference between:
function Person() {};
Person.walk = function() {};
and...
function Person() {};
Person.prototype.walk = function() {};
It seems that the second way is the convention for constructors, but I don't understand the difference and why it is done that way. Thanks!
回答1:
In the first case:
function Person() {};
Person.walk = function() {};
You will be able to call the function only with:
Person.walk();
If you create an instance of Person, you won't be able to call the method:
p = new Person();
p.walk() // -> TypeError: Object #<Person> has no method 'walk'
In the other hand, if you use the prototype you will only be able to call the method through an instance.
回答2:
The first function has no relationship with an object instance of that constructor function, you can consider it like a 'static method'.
The second function, as you are extending the constructor function prototype, it will be available to all the object instances created with the new keyword
Example:
// constructor function
function MyClass () {
var privateVariable; // private member only available within the constructor fn
this.privilegedMethod = function () { // it can access private members
//..
};
}
// A 'static method', it's just like a normal function
// it has no relation with any 'MyClass' object instance
MyClass.staticMethod = function () {};
MyClass.prototype.publicMethod = function () {
// the 'this' keyword refers to the object instance
// you can access only 'privileged' and 'public' members
};
var myObj = new MyClass(); // new object instance
myObj.publicMethod();
MyClass.staticMethod();
回答3:
The prototype is kind of a template for creating instances, unlike the constructor. Note that prototype's members are not actually copied to instances, instead, instances draw on prototype's resources, unless the resource is already owned by the instance.
var Class = function () {};
Class.prototype.a = 1;
Class.prototype.b = 2;
// creates a new instance named "c"
var c = new Class();
c.b = 3;
console.log(
c.hasOwnProperty('a'), // -> false
c.hasOwnProperty('b'), // -> true
c.a, // -> 1 (prototype)
c.b, // -> 3 (instance)
Class.prototype.b // -> 2 (prototype)
);
来源:https://stackoverflow.com/questions/21373165/what-is-the-difference-between-assigning-a-function-directly-to-a-constructor-ve