Object.prototype using 'this'
Object.prototype using 'this'
这可能是基本的,也可能是不可能的,我可能完全误解了,但我是一个初学者,试图了解使用Object.prototype向对象添加方法的工作原理。
解释我的问题的最好方法是首先显示以下内容:
Object.prototype.printHTML = function() {
alert(this.innerHTML);
};
this
似乎只是简单地引用Object.prototype.printHTML(提醒HTML注意上面.中=符号后面的内容
我的问题是,你能直接引用所使用的对象吗?
因此,下面将提醒"测试段落":
<body>
<p id='test'>Test Paragraph</p>
<script>
Object.prototype.printHTML = function() {
alert(this.innerHTML);
};
document.getElementById("test").printHTML; //this would alert "Test Paragraph"
//currently alerts "function() {alert(this.innerHTML);}
</script>
</body>
我知道这个例子毫无意义(因为document.getElementById("test").innerHTML;
正是我所需要的),但我只是试图理解使用Object.prototype创建方法,我不知道如何访问该方法运行的对象。
感谢
你真的很接近,而是做这个
<body>
<p id='test'>Test Paragraph</p>
<script>
Object.prototype.printHTML = function() {
alert(this.innerHTML);
};
document.getElementById("test").printHTML(); //<--- HERE WE ADD THE PARENTHESIS
//currently alerts "function() {alert(this.innerHTML);}
</script>
</body>
您访问printHTML
时将其作为一个属性,而不是一个函数并执行它。因此,您将函数作为文本获取。
相关文章:
- Object.prototype using 'this'
- this.prototype 和 module.exports 之間的差異
- MyObj.prototype. vs this
- 为什么 String.prototype 中的“this”指的是对象类型,而不是字符串类型
- [].slice.call(this) vs array.prototype.call(this)
- JavaScript:继承时this.watever和prototype.whatever之间的区别
- this.method与prototype.method有什么区别
- Node.js:事件的关系.EventEmitter.call(this)和Obj.prototype.__proto_
- 为什么可以't通过this指针设置prototype的值类型属性
- TypeError:调用Function.protype.method()时,this.prototype未定义
- var prototype=new this();有人能解释一下John resig在他的类继承博客中使用的这句话吗
- this.constructor.prototype.constructor.apply在js中是什么意思?
- 为什么调用array.prototype. foreach .call()时将数组设置为THIS对象不能工作?
- Using `this` vs Object.create(prototype)
- Javascript使用this.prototype设置prototype
- 使用'this'在构造函数中使用prototype属性
- Function.prototype.call在严格模式之外改变this的类型;为什么
- 为什么要将prototype用于方法而不是this.methodName
- Javascript -这两者之间有区别吗?Foo和this.prototype.foo
- 'this'在Array.prototype.slice.call(arguments)中设置上下文