为什么会出现这种情况?__ proto__ vs prototype? [英] Why this behaviour?__proto__ vs prototype?

查看:91
本文介绍了为什么会出现这种情况?__ proto__ vs prototype?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    function Obj1(name){
        this.__proto__={
            Name:name,
            getName:function(){
                alert(this.Name); 
            }


        };

    }

    function Obj2(name){
       this.prototype={
           Name:name,
           getName:function(){
           alert(this.Name); 
           };


       };

    }
    x=new Obj1("blue shark");
    z=new Obj2("red shark");
    x.getName();
    z.getName();// error:z.getName() is not a function

两者有什么区别?有人说 prototype 仅用于构造函数,但在这种情况下它不起作用....而不是 __ proto __ 为什么工作?

What is the difference between the two?Some say prototype is used for constructor functions only but in this case it doesn't work.... instead the __proto__ work why?

推荐答案

__ proto __ (这不是标准的(但可能很快)))设置对象的原型。

.prototype 设置通过调用其设置的函数创建的对象的原型作为构造函数使用 new

另外值得一提的是 Object.create

Also worth mentioning is Object.create

以下是示例:

伪古典与 .prototype

function Car(){
   this.x = 15;
}
Car.prototype.y = 10;

var g = new Car();
g.y; // this is 10;

使用 __ proto __ (不要使用此!):

Using __proto__ (don't use this!):

var g = {x:15};
g.__proto__ = {y:10};
g.y; // this is 10;

这种方式是正确的,并且不使用 new

This way is correct, and does not use constructors with new:

var g = Object.create({y:10}); //creates x with prototype {y:10}
g.x = 15;
g.y; // this is 10

这是一个有趣的MDN教程,涵盖了这些

这篇关于为什么会出现这种情况?__ proto__ vs prototype?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆