prototype - javascript 如何实现类似 PHP 的 __set __get

WBOY
Release: 2016-06-06 20:39:52
Original
1331 people have browsed it

JS

如何让JS实现类似PHP的 __set __get方法?

<code>html</code><code><input type="text" id="ipt1" name="username" value="1" _tipstxt="提示内容">
<script type="text/javascript">
var username = document.getElementById('ipt1');
alert(username._tipsTxt);
alert(username._maxLen); //这些类似 _maxLen 是不确定的
</script>
</code>
Copy after login
Copy after login

属性

<code>javascript</code><code>prototype
</code>
Copy after login
Copy after login

回复内容:

JS

如何让JS实现类似PHP的 __set __get方法?

<code>html</code><code><input type="text" id="ipt1" name="username" value="1" _tipstxt="提示内容">
<script type="text/javascript">
var username = document.getElementById('ipt1');
alert(username._tipsTxt);
alert(username._maxLen); //这些类似 _maxLen 是不确定的
</script>
</code>
Copy after login
Copy after login

属性

<code>javascript</code><code>prototype
</code>
Copy after login
Copy after login

估计你是想要这个:

<code>username.__defineGetter__('_tipsTxt', function(){return this.getAttribute('_tipsTxt');});
username.__defineSetter__('_tipsTxt', function(txt){this.setAttribute('_tipsTxt', txt);});
</code>
Copy after login

JS属性自带set,get功能啊..=_= 请看DEMO:http://jsfiddle.net/7jfmafkd/
具体请查阅:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template