gpt4 book ai didi

JavaScript - 原型(prototype)

转载 作者:行者123 更新时间:2023-11-30 07:29:44 30 4
gpt4 key购买 nike

我正在努力获得更好的 JavaScript 实用知识。所以,我买了 Douglas Crockford 的书“JavaScript the good parts”。

我现在很难掌握原型(prototype)。在我点击//PROTOTYPE Example 之前,下面的所有内容似乎都可以在我的浏览器中使用。有人可以看看它,看看为什么我无法从中获得任何输出。 (除非我注释掉所有原型(prototype)代码,否则我的页面返回空白)

感谢您的帮助。

巴里

var stooge = { 
"first-name": "Jerome",
"last-name": "Howard",
"nickname": "J",
"profession" : 'Actor'
};

// below is augmenting
var st = stooge;
st.nickname = "curly";
// st.nickname and nick are the same because both are ref's to the same object
var nick = st.nickname;


document.writeln(stooge['first-name']); //expect Jerome -- this is "suffix" retrieval
document.writeln(st.nickname); //expect "curly" -- this is "notation" retrieval
document.writeln(nick); //expect "curly"
document.writeln(stooge.profession);


//PROTOTYPE EXAMPLE;
if (typeof Object.create !== 'function')
{
object.create = function(o) {
var F = function () {};
F.prototype = o;
return new F();
};
var another_stooge = Object.create(stooge);
another_stooge['first-name'] = 'Barry';
document.writeln(another_stooge['first-name']);
// the below should be inherited from the prototype therefore "Actor"
document.writeln(another_stooge.profession);

最佳答案

您在分配给 object.create 的函数表达式末尾缺少右大括号,而且您还没有在 object.create = function(o) { 中将 Object 大写。

//PROTOTYPE EXAMPLE; 
if (typeof Object.create !== 'function')
{
Object.create = function(o) { // <--- "Object" instead of "object"
var F = function () {};
F.prototype = o;
return new F();
};
} // <--- Closing brace was missing

关于JavaScript - 原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1630141/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com