相关疑难解决方法(0)

使用"Object.create"而不是"new"

Javascript 1.9.3/ECMAScript 5介绍Object.create道格拉斯·克罗克福德等人长期以来一直在倡导.如何new在下面的代码中替换Object.create

var UserA = function(nameParam) {
    this.id = MY_GLOBAL.nextId();
    this.name = nameParam;
}
UserA.prototype.sayHello = function() {
    console.log('Hello '+ this.name);
}
var bob = new UserA('bob');
bob.sayHello();
Run Code Online (Sandbox Code Playgroud)

(假设存在MY_GLOBAL.nextId).

我能想到的最好的是:

var userB = {
    init: function(nameParam) {
        this.id = MY_GLOBAL.nextId();
        this.name = nameParam;
    },
    sayHello: function() {
        console.log('Hello '+ this.name);
    }
};
var bob = Object.create(userB);
bob.init('Bob');
bob.sayHello();
Run Code Online (Sandbox Code Playgroud)

似乎没有任何优势,所以我想我没有得到它.我可能过于新古典主义了.我应该如何使用MY_GLOBAL.nextId创建用户'bob'?

javascript constructor new-operator object-create

364
推荐指数
8
解决办法
17万
查看次数

原型继承 - 写作

所以我有这两个例子,来自javascript.info:

例1:

var animal = {
  eat: function() {
    alert( "I'm full" )
    this.full = true
  }
}

var rabbit = {
  jump: function() { /* something */ }
}

rabbit.__proto__ = animal 

rabbit.eat() 
Run Code Online (Sandbox Code Playgroud)

例2:

function Hamster() {  }
Hamster.prototype = {
  food: [],
  found: function(something) {
    this.food.push(something)
  }
}

// Create two speedy and lazy hamsters, then feed the first one
speedy = new Hamster()
lazy = new Hamster()

speedy.found("apple")
speedy.found("orange")

alert(speedy.food.length) // 2
alert(lazy.food.length) // 2 (!??)
Run Code Online (Sandbox Code Playgroud)

从示例2开始:当代码到达时 …

javascript inheritance prototype

130
推荐指数
2
解决办法
1万
查看次数