gpt4 book ai didi

javascript - 为什么添加到原型(prototype)的方法没有给出 "not defined"的错误?

转载 作者:行者123 更新时间:2023-12-02 17:19:46 25 4
gpt4 key购买 nike

我不理解原型(prototype)。据我了解,这段代码应该可以工作。我已经使用 Object.create 创建了一个原型(prototype),并向原型(prototype)添加了一个方法,但我不断收到错误。那么如何让这段代码正常工作呢?让我换个说法,如何正确编写代码?

// base function
function person()
{
this.name;
this.type;
}

//create instance of function
var a = new person();
a.name = 'ha';
console.log(a.name);

//as opposed to creating instance like above, have new object "b" have the function person as its prototype
var b = Object.create(person);
b.name = 'ho';
console.log(b.name);

//add the method height to the prototype, aka. underlying object "person"
b.prototype.height = function(h) {return h * 2;};

console.log(b.height(5));

//scratch head and ask SO why this doesn't work
/*
Exception: b.height is not a function
@Scratchpad/3:26
*/

最佳答案

//as opposed to creating instance like above, have new object "b" have the 
//function person as its constructor, person.prototype as its prototype object
var b = Object.create(person); //this is wrong
var b = Object.create(person.prototype); //this is right. b now has person() as its constructor

Object.create() 方法使用指定的原型(prototype)对象和属性创建一个新对象。请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create

//this wouldnt work because b is an object, not a constructor. 
//If you want b to inherit the height method, define it on the it's constructor's
//prototype object which is person.prototype
//(NOTE that you created b from person.prototype)
person.prototype.height = function(h) {return h * 2;};

关于javascript - 为什么添加到原型(prototype)的方法没有给出 "not defined"的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24073287/

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