Pros/Cons of not using the prototype chain and returning objects instead
I'm starting to understand javascript, but are there any benefits of using javascript objects like so ...
var Person(name, age) {
var obj = {
species: "Homo sapien",
location: "Earth"
};
obj.name = name;
obj.age = age;
return obj;
}
var Mike = Person("Mike", 17); // => { ... name: "Mike", age: 17}
versus the standard
var personProtoype = {
name: "anon",
age: 0,
species: "Homo sapien",
location: "Earth"
}
var Person = function(name, age) {
this.name = name;
this.age = age;
}
Person.prototype = personPrototype;
var Mike = new Person("Mike", 17);
because it seems to use less code and easier to implement and understand. "Inheritance" is also pretty straightforward with the first method too.
var Student(name, age, major) {
var obj = Person(name, age); // => { ... name: name, age: age}
obj.major = major; // => { ... name: name, age: age, major: major}
return obj;
}
I understand that the following doesn't use prototype chains at all, just functions that simply construct objects. I was just wondering if there was any benefit of doing things this way? Maybe to have objects that don't look back at a huge chain of prototypes? (if that type of behavior is ever desired)
I can't think of any advantages beyond the ones you listed, although there may be some. Here are some of the disadvantages:
No instanceof
testing. Using the Person
implementations in your question, slightly renamed:
var Mike1 = Person_no_prototype("Mike", 17);
var Mike2 = new Person_with_prototype("Mike", 17);
console.log(Mike1 instanceof Person_no_prototype); // false
console.log(Mike2 instanceof Person_with_prototype); // true
When methods exist, uses more memory. Consider an implementation of a greet
method, put on either obj
or Person.prototype
:
/* obj or Person.prototype */.greet = function greet() {
alert("Hi there, " + this.name + "!");
};
Using a prototype, the greet
function is created only once. Without a prototype, you create a new function each time, with whatever overhead that implies.
上一篇: MooTools和Array原型
下一篇: 不使用原型链和返回对象的优点/缺点