JavaScript 中的原型链

发布于 2024-10-01 09:39:46 字数 1706 浏览 6 评论 0原文

我正在读一本名为《JavaScript 模式》的书,但我认为其中有一部分令人困惑。

这家伙实际上在书中引入了 klass 设计模式,他在其中一点一点地开发了它。他首先提出了这个问题:

function inherit(C, P) {
C.prototype = P.prototype;
}

他说:

这为您提供了简短而快速的原型链查找,因为所有对象实际上共享相同的原型。但这也是一个缺点,因为如果一个孩子或孙子 继承链下游的某处修改原型,它会影响所有父母和祖父母。

但是,我实际上尝试修改 Child 中的原型 say() ,它对 Parent 没有影响,事实上 Child 仍然指向 Parent并完全忽略了它自己的同名原型,这是有道理的,因为它指向不同的内存位置那么这家伙怎么能说这样的话呢?下面证明了我的观点:

function Parent(){}

Parent.prototype.say = function () {
return 20;
};

function Child(){
}

Child.prototype.say = function () {
return 10;
};

inherit(Child, Parent);

function inherit(C, P) {
C.prototype = P.prototype;
 } 

 var parent = new Parent();
var child = new Child();


var child2 = new Child()
alert(child.say(); //20
alert(parent.say()); //20
alert(child2.say()); //20

孩子或孙子都不可能修改原型!

任何 他说,解决继承链上意外修改父原型的可能性(我无法重现)的问题的解决方案是打破父原型和子原型之间的直接链接,同时从中受益。他提供了以下解决方案:

function inherit(C, P) {
var F = function () {};
F.prototype = P.prototype;
C.prototype = new F();
}

问题是它输出与其他模式相同的精确值:

function Parent(){}

Parent.prototype.say = function () {
return 20;
};

function Child(){
}

 Child.prototype.say = function () {
return 10;
};

inherit(Child, Parent);

function inherit(C, P) {
var F = function () {};
F.prototype = P.prototype;
C.prototype = new F();
}

var parent = new Parent();
var child = new Child();


var child2 = new Child()
alert(child.say(); //20
alert(parent.say()); //20
alert(child2.say()); //20

空函数以某种方式破坏链接是没有意义的。 F又指向Parent的原型。所以它们仍然指向相同的内存位置。上面对此进行了演示,其中它输出与第一个示例相同的精确值。我不知道这位作者想要证明什么,也不知道为什么他提出的主张对我来说不合时宜,而且我无法复制。

感谢您的回复。

I'm reading a book called JavaScript patterns but there's one part where I think the guy is confusing.

The guy actually led up in the book to the klass design pattern, where he developed it piece by piece. He first he presents the problem:

function inherit(C, P) {
C.prototype = P.prototype;
}

He says:

"This gives you short and fast prototype chain lookups because all objects actually share the same prototype. But that’s also a DRAWBACK because if one child or grandchild
somewhere down the inheritance chain MODIFIES the prototype, it AFFECTS all parents and grandparents.
"

However, I actually tried to modify the prototype say() in Child and it had no affect on Parent and in fact Child still pointed to Parent and completely ignored its own prototype of same name, which makes sense since it's pointing to a different memory position. So how can the guy say something like that? Below proves my point:

function Parent(){}

Parent.prototype.say = function () {
return 20;
};

function Child(){
}

Child.prototype.say = function () {
return 10;
};

inherit(Child, Parent);

function inherit(C, P) {
C.prototype = P.prototype;
 } 

 var parent = new Parent();
var child = new Child();


var child2 = new Child()
alert(child.say(); //20
alert(parent.say()); //20
alert(child2.say()); //20

It's impossible for any child or grandchild to modify the prototype!

This leads to my second point. He says the solution to the problem of the possibility of accidentially modifying parent prototypes down inheritance chain (which I can't reproduce) is to break the direct link between parent’s and child’s prototype while at the same time benefiting from the prototype chain. He offers the following as a solution:

function inherit(C, P) {
var F = function () {};
F.prototype = P.prototype;
C.prototype = new F();
}

The problem is this outputs the same exact values as the other pattern:

function Parent(){}

Parent.prototype.say = function () {
return 20;
};

function Child(){
}

 Child.prototype.say = function () {
return 10;
};

inherit(Child, Parent);

function inherit(C, P) {
var F = function () {};
F.prototype = P.prototype;
C.prototype = new F();
}

var parent = new Parent();
var child = new Child();


var child2 = new Child()
alert(child.say(); //20
alert(parent.say()); //20
alert(child2.say()); //20

It doesn't make sense that an empty function somehow breaks a link. In fact, the Child points to F and F in turn points to the Parent's prototype. So they are ALL still pointing to the same memory position. This is demonstrated above, where it outputs the same exact values as the first example. I have no clue what this author is trying to demonstrate and why he makes claims that don't gel for me and that I can't reproduce.

Thanks for response.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

叹梦 2024-10-08 09:39:46

对于您的第一点:

这个人想说的是,如果您在创建实例之后修改原型,则子级和父级的方法都会发生变化。

例如:

function inherit(C, P) {
  C.prototype = P.prototype;
} 

function Parent(){}
function Child(){}

inherit(Child, Parent);

Parent.prototype.say = function () {
  return 20;
};

var parent = new Parent();
var child = new Child();


// will alert 20, while the method was set on the parent.
alert( child.say() );

当您更改子级的构造函数(与父级共享)时,也会发生同样的事情。

// same thing happens here, 
Child.prototype.speak = function() {
  return 40;
};

// will alert 40, while the method was set on the child
alert( parent.speak() );

关于第二点:

function inherit(C, P) {
  var F = function () {};
  F.prototype = P.prototype;
  C.prototype = new F();
}

新的继承函数实际上会将父级的构造函数与子级分开,因为它不再指向同一个对象,但现在它指向新创建的函数的原型,该原型与家长。因此,您实际上创建了父级构造函数的本地副本,然后创建该副本的新实例,该实例返回所有构造函数方法和属性。现在通过更改子级的构造函数,不会影响父级。

function inherit(C, P) {
  var F = function () {};
  F.prototype = P.prototype;
  C.prototype = new F();
}

function Parent(){}
function Child(){}

inherit(Child, Parent);

// same thing happens here, 
Child.prototype.speak = function() {
  return 40;
};

var parent = new Parent();

// will throw an error, because speak is undefined
alert( parent.speak() );

For your first point:

What this guy is trying to say, is that the methods for both child and parent will change if you modify the prototype after you created instances.

For example:

function inherit(C, P) {
  C.prototype = P.prototype;
} 

function Parent(){}
function Child(){}

inherit(Child, Parent);

Parent.prototype.say = function () {
  return 20;
};

var parent = new Parent();
var child = new Child();


// will alert 20, while the method was set on the parent.
alert( child.say() );

The same thing happens when you change the child's constructor (which is shared with the parent).

// same thing happens here, 
Child.prototype.speak = function() {
  return 40;
};

// will alert 40, while the method was set on the child
alert( parent.speak() );

And about your second point:

function inherit(C, P) {
  var F = function () {};
  F.prototype = P.prototype;
  C.prototype = new F();
}

The new inheriting function will actually separate the constructor of the parent from the child, because it's not pointing to the same object anymore, but now it's pointing to a prototype of a newly created function that has nothing to do with the parent. So, you actually create a local copy of the parent's constructor, and then create a new instance of the copy, which returns all constructor methods an properties. By changing the constructor of the child now, it will not affect the parent.

function inherit(C, P) {
  var F = function () {};
  F.prototype = P.prototype;
  C.prototype = new F();
}

function Parent(){}
function Child(){}

inherit(Child, Parent);

// same thing happens here, 
Child.prototype.speak = function() {
  return 40;
};

var parent = new Parent();

// will throw an error, because speak is undefined
alert( parent.speak() );
花开半夏魅人心 2024-10-08 09:39:46

事实上,你可以通过指向另一个原型来更改原型对象,这是正常的 JavaScript 行为。 JavaScript 的原始值是不可变的,但对象和数组不是。我将用简单的例子来解释它:

var person = {name: 'greg', age: 20};

>>>person.name; //prints 'greg'

>>>person.age; //prints 20

var a = person;

>>>a.name; //prints 'greg'

a.name = 'peter';

>>>a.name; //prints 'peter'

>>>person.name; //prints 'peter'

//I've changed person.name through a.name. That's why objects in JavaScript are called mutable

数组具有相同的行为:

var arr = ['first', 'second', 'third'],
    newArr = arr;

newArr.pop();

>>>newArr; //prints ['first', 'second']

>>>arr; //prints ['first', 'second']

//Frist array was also changed

让我们看看字符串数字和布尔值(原始数据类型):

var str = 'hello world',

    newStr = str;

>>>str; //prints 'hello world'

>>>newStr; //prints 'hello world'

>>>newStr.toUpperCase(); //prints 'HELLO WORLD'

>>>str; //prints 'hello world'

>>newStr; //prints 'hello world'

//Numbers and booleans have similiar behavior

我遇到了同样的问题,但我修复了它。看,我已经评论了你的代码,其中的一些提示应该对你有帮助:

function Parent(){}

Parent.prototype.say = function () {
return 20;
};

function Child(){
}



/**
*
* The area you should examine i've selected below.
*
*/

//Start BUG

//new say method will not affect the Parent.prototype beacuse it wasn't assigned yet
Child.prototype.say = function () {
return 10;
};

//rewrite Child.prototype and all it's methods with Parent.prototype
inherit(Child, Parent);

//End BUG



function inherit(C, P) {
C.prototype = P.prototype;
 } 

var parent = new Parent();
var child = new Child();


var child2 = new Child()
alert(child.say(); //20
alert(parent.say()); //20
alert(child2.say()); //20

这里的问题是,你不是复制和更改 Parent.prototype,而是创建新的 Child.prototype.say 方法,然后重写整个 Child .prototype 对象通过 Parent.prototype 赋值。只要改变他们的顺序就应该可以正常工作。

The fact that you can change prototype object by pointing another prototype to it is normal JavaScript behavior. JavaScript's primitive values are immutable but objects and arrays aren't. I'll explain it with simple example:

var person = {name: 'greg', age: 20};

>>>person.name; //prints 'greg'

>>>person.age; //prints 20

var a = person;

>>>a.name; //prints 'greg'

a.name = 'peter';

>>>a.name; //prints 'peter'

>>>person.name; //prints 'peter'

//I've changed person.name through a.name. That's why objects in JavaScript are called mutable

Arrays have the same behavior:

var arr = ['first', 'second', 'third'],
    newArr = arr;

newArr.pop();

>>>newArr; //prints ['first', 'second']

>>>arr; //prints ['first', 'second']

//Frist array was also changed

Let's look at strings numbers and booleans(primitive data types):

var str = 'hello world',

    newStr = str;

>>>str; //prints 'hello world'

>>>newStr; //prints 'hello world'

>>>newStr.toUpperCase(); //prints 'HELLO WORLD'

>>>str; //prints 'hello world'

>>newStr; //prints 'hello world'

//Numbers and booleans have similiar behavior

I had the same issue but i fixed it. Look, i've commented your code, some hints in it should help you:

function Parent(){}

Parent.prototype.say = function () {
return 20;
};

function Child(){
}



/**
*
* The area you should examine i've selected below.
*
*/

//Start BUG

//new say method will not affect the Parent.prototype beacuse it wasn't assigned yet
Child.prototype.say = function () {
return 10;
};

//rewrite Child.prototype and all it's methods with Parent.prototype
inherit(Child, Parent);

//End BUG



function inherit(C, P) {
C.prototype = P.prototype;
 } 

var parent = new Parent();
var child = new Child();


var child2 = new Child()
alert(child.say(); //20
alert(parent.say()); //20
alert(child2.say()); //20

The problem here is, that instead of copying and changing the Parent.prototype you creating new Child.prototype.say method and right after it you rewriting the whole Child.prototype object through Parent.prototype assignment. Just change their order and it should work fine.

路还长,别太狂 2024-10-08 09:39:46

如果您在继承后更改原型,您会看到它也会更改父级的原型:

function Parent(){}

Parent.prototype.say = function () {
return 20;
};

function Child(){
}

inherit(Child, Parent);

Child.prototype.say = function () {
return 10;
};

function inherit(C, P) {
C.prototype = P.prototype;
 } 

 var parent = new Parent();
var child = new Child();


var child2 = new Child()
alert(child.say()); //10
alert(parent.say()); //10
alert(child2.say()); //10

如果您使用 inherit 函数的修改版本,则 Child原型保持独立。

If you change the prototype after inheriting it, you see it change the prototype for the parent also:

function Parent(){}

Parent.prototype.say = function () {
return 20;
};

function Child(){
}

inherit(Child, Parent);

Child.prototype.say = function () {
return 10;
};

function inherit(C, P) {
C.prototype = P.prototype;
 } 

 var parent = new Parent();
var child = new Child();


var child2 = new Child()
alert(child.say()); //10
alert(parent.say()); //10
alert(child2.say()); //10

If you use the modifed version of the inherit function, the Child and Parent prototypes remain separate.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文