有什么区别
var A = function () {
this.x = function () {
//do something
};
};
Run Code Online (Sandbox Code Playgroud)
和
var A = function () { };
A.prototype.x = function () {
//do something
};
Run Code Online (Sandbox Code Playgroud) 我一直在使用javascript,但从未学过语言超过基础知识.我正在阅读John Resig的"Pro Javascript技术" - 我想出了一些问题,但我没有在书中或谷歌上找到答案.
约翰在他的书中给出了这个例子:
功能#1
function User( name, age ){
this.name = name;
this.age = age;
}
// Add a new function to the object prototype
User.prototype.getName = function(){
return this.name;
};
User.prototype.getAge = function(){
return this.age;
};
var user = new User( "Bob", 44 );
console.log("User: " + user.getName() + ", Age: " + user.getAge());
Run Code Online (Sandbox Code Playgroud)
我还在学习原型属性,所以我尝试写类似的东西:
功能#2
function User (name, age ) {
this.name = name;
this.age = age;
this.getName = function() {
return this.name; …Run Code Online (Sandbox Code Playgroud)