JavaScript-面向对象-扩展内置对象方法

建立自定义对象的方法

 function Person( ) { }
 Person.prototype={
       constructor:Person,
       name:"Jack",
       age:100,
       sayHi:function ( ) {
             alert("hello"+this.name);
       }
 };
 var p1=new Person( );
 p1.sayHi(); 

扩展内置对象(String)的方法

String.prototype={
        constructor:this,
        run:function () {
            alert("success!");
        }
    };

    var n="####";
    n.run();

后面的constructor属性不指向String对象(前面的constructor属性指向Person对象),这是为什么呢?

阅读 3.4k
2 个回答

你前面写了Person,后面写了this

首先,看一下Stringprototype属性:

Object.getOwnPropertyDescriptor(String, 'prototype');

// 结果(环境:Chrome 51)
{value: String, writable: false, enumerable: false, configurable: false}

看到没有,writablefalse,是没法修改的。所以你的赋值无效。String作为一个内置的构造函数,是不允许你随便修改它的属性的。

即使是可以修改的,像你那样修改后prototype也是不会指向String的,而是需要这样:

String.prototype={
    constructor: String,
    run:function () {
        alert("success!");
    }
};

var n="####";
n.run();

用this是不行的。因为你代码中的this是位于全局作用域的,this是全局对象,例如window

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题