在另一个问题中,用户指出该new关键字使用起来很危险,并提出了一种不使用的对象创建解决方案new.我不相信这是真的,主要是因为我使用了Prototype,Scriptaculous和其他优秀的JavaScript库,并且每个人都使用了new关键字.
尽管如此,昨天我在YUI剧院观看道格拉斯·克罗克福德的演讲,他说的完全一样,他new在代码中不再使用关键字(Crockford on JavaScript - Act III:Function the Ultimate - 50:23分钟).
使用new关键字"不好" 吗?使用它有哪些优缺点?
什么是构建的用法:function F() { if (!(this instanceof F)) { return new F() }; ... }?
我在一个pty.jsfor Node中找到了这个.这是原始代码:
function Terminal(file, args, opt) {
if (!(this instanceof Terminal)) {
return new Terminal(file, args, opt);
}
var self = this
, env
, cwd
, name
, cols
, rows
, term;
-------------------SKIP-----------------------------------
Terminal.total++;
this.socket.on('close', function() {
Terminal.total--;
self._close();
self.emit('exit', null);
});
env = null;
}
Run Code Online (Sandbox Code Playgroud) 我一直在阅读了关于克罗克福德的垫片,以防止原型的改写,并了解它的不是结束,所有的/是的解决办法的时候.我也明白,ES5 Shim可能是一个可行的替代品.我还阅读了这篇文章,它提供了一个更强大,更安全的选择.
不过,我想知道他的Object.create垫片是什么"说"然后"做".如果我的解释评论是正确的,有人可以告诉我吗?
if (typeof Object.create === 'undefined') {
//If the browser doesn't support Object.create
Object.create = function (o) {
//Object.create equals an anonymous function that accepts one parameter, 'o'.
function F() {};
//Create a new function called 'F' which is just an empty object.
F.prototype = o;
//the prototype of the 'F' function should point to the
//parameter of the anonymous function.
return new F();
//create a new constructor function based off of …Run Code Online (Sandbox Code Playgroud) 我最近一直在阅读"有效的JavaScript",我遇到了这个问题.
作者解释了如何使构造函数与新的无关,因为如果开发人员忘记使用'new'关键字调用Constructor,'this'指的是'Window'.那讲得通.令我困惑的是他实施的目的.
他建议像这样设置你的构造函数.
var Person = function(name, age){
var that = this instanceof Person ? this : Object.create(Person.prototype);
that.name = name;
that.age = age;
return that;
}
Run Code Online (Sandbox Code Playgroud)
那讲得通.您检查'this'是否是Person的实例,这意味着它是使用'new'关键字调用的.如果不是,则创建一个与"this"相同的新Object并返回该对象.
我的问题是这个.如果你正在设置一个与'this'完全相同的新Object,那么我们不能再担心是否通过前面的'this'调用了构造函数而只是创建了新对象.
var Person = function(name, age){
var that = Object.create(Person.prototype);
that.name = name;
that.age = age;
return that;
}
Run Code Online (Sandbox Code Playgroud)
为什么不担心'this'和'new',为什么不总是像上面那样创建我们的构造函数?
我认为这样做是为了看看这个对象是否已经被实例化并且是否存在于范围内?为什么我们需要使用三等号来确定?
function viewmodel(parent) {
if (false === (this instanceof viewmodel)) {
return new viewmodel(parent);
}
};
Run Code Online (Sandbox Code Playgroud)