gpt4 book ai didi

Javascript:[用户定义原型(prototype)] 中的变量不可用

转载 作者:行者123 更新时间:2023-11-30 13:30:15 24 4
gpt4 key购买 nike

我通过 Web 开发人员的专业 JavaScript 这本书来玩 javascript。我在 6.2.6 节中练习了一个例子。代码如下:

function creatPrototype(subType, superType) 
{
function subTypePrototype(){};
subTypePrototype.prototype = superType.prototype;
subTypePrototype.constructor = subType;
subTypePrototype.str = "say";
return new subTypePrototype();
}

function Person(name, age)
{
this.name = name;
this.age = age;
}
Person.prototype.say = function(){
writeln("bill say");
}


function itMan(name, age){
Person.apply(this, arguments);
}
itMan.prototype = creatPrototype(itMan, Person);


var Bill = new itMan("bill", 25);

writeln(itMan.prototype.str); //expect "say"
writeln(Person.prototype == itMan.prototype.prototype); //expect true
Bill.say(); //expect "bill say"

结果是:

undefined

False

bill say

为什么?

  1. itMan.prototype.str 假设“说”

  2. Person.prototype AND itMan.prototype.prototype 应该指向同一个对象

  3. Bill.say() 运行正确,所以原型(prototype)链没问题。

最佳答案

您必须考虑哪些属性属于构造函数,哪些属性属于实例prototype 是函数的属性,但是 constructorstr 应该都是实例的属性。

应该这样做:

function createPrototype(subType, superType) 
{
function subTypePrototype(){};
subTypePrototype.prototype = superType.prototype;

var newPrototype = new subTypePrototype();

newPrototype.constructor = subType;
newPrototype.str = "say";
return newPrototype;
}

但是,因为你也是 passong subType,你实际上可以直接分配原型(prototype):

function inherit(subType, superType) 
{
function tconstr(){};
tconstr.prototype = superType.prototype;

subType.prototype = new tconstr();

subType.prototype.constructor = subType;
subType.prototype.str = "say";
}

然后用

调用它
inherits(itMan, Person);

Person.prototype AND itMan.prototype.prototype should point to a same object

请记住,prototype函数 的属性,而不是对象的属性。但是 itMan.prototype 是一个对象。除非明确引用对象原型(prototype),否则无法访问它(但我不会这样做)。

在 ECMAScript 5 中,有一种方法可以使用 Object.getPrototypeOf [MDN] 获取原型(prototype)。 .不过,这仅适用于较新的浏览器。

这是一个working example你的代码。

关于Javascript:[用户定义原型(prototype)] 中的变量不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7036002/

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