我正在看 Douglas Crockford 系列中 new
运算符的代码。
function Shane(name){
this.name = name;
}
var sha = new Shane("name");
console.log(sha);
上面的代码只是创建了一个新的 Shane 对象,并将其构造函数设置为 Shane,将 Prototype 设置为 Object.prototype:
function new(func, args){
var that = Object.create(func.prototype);
result = func.apply(that, args);
return (typeof result==='object' && result) || that;
}
任何人都可以向我解释这段代码的作用并给我一个例子吗?
最佳答案
The above code just creates a new Shane object and sets its constructor to Shane and Prototype to Object.prototype.
不完全是。对象 sha
的原型(prototype)将是 Shane.prototype
。 Shane.prototype
的原型(prototype)将是 Object.prototype
。
您提供的函数(最好命名为 new2
、gnu
、knew
或 new
的其他变体,因为它是一个语法错误)执行与语言中的 new
运算符相同的三个基本操作。
new Shane(arg1, ..., argN)
做这三件事:
- 创建一个新的空对象并将其 [[Prototype]] 属性设置为 Shane.prototype。
- 在新对象的上下文中应用函数
Shane
和参数arg1
, ...argN
,可能接收返回值. - 如果收到返回值,则将其返回。如果没有返回这个新创建的对象。
new2
函数(让我们这样调用它)做同样的事情。所以你可以像这样使用它:
var sha2 = new2(Shane, ["name"]);
并返回与上面的 sha
非常相似的内容。
关于javascript - 理解 JavaScript 中的 new 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27977044/