建立自定义对象的方法
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对象),这是为什么呢?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
你前面写了Person,后面写了this
首先,看一下
String的prototype属性:看到没有,
writable是false,是没法修改的。所以你的赋值无效。String作为一个内置的构造函数,是不允许你随便修改它的属性的。即使是可以修改的,像你那样修改后
prototype也是不会指向String的,而是需要这样:用this是不行的。因为你代码中的
this是位于全局作用域的,this是全局对象,例如window。